Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

A perl Query regarding the foreach loop

Status
Not open for further replies.

kaushikrvs

Member level 5
Member level 5
Joined
Jan 27, 2017
Messages
82
Helped
0
Reputation
0
Reaction score
0
Trophy points
6
Activity points
613
@list_1 = (1,2,3,4,5,6,7,8,9,10);
@list_odd = @list_1[0,2,4,6,8];
@list_prime = @list_1[1,2,4,6];

foreach $x (@list_odd) { print @list_odd[$x];}


Output : 3 , 7

For some reason, it's not showing the remaining elements of the list. Can anyone help me with it?
 

You are doing 2 levels of dereferencing in the foreach loop.
If you just printed $x you would get 1, 3, 5, 7 and 9.
list_odd[1] is 3 (given a 0-base index) - the first number you see printed
list_odd[3] is 7 - the 2nd number printed
list_odd[5] is beyond the array bounds and so doesn't happen
Pencil and paper can go a long way in designing things as well as testing the underlying logic.
Susan
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top