in reply to NEWBIE Brain Teaser
HOW THE CODE WORKS
So what's going on here? At first glance, this bit of code seems pretty straightforward. Line 1 assigns numbers 1 thru 5 to the first 5 elements of the @list array. Lines 3-6 do nothing but declare variables. The foreach loop starting on line 8 assigns each element of @list to $each and multiplies the contents of $each by two. It then assigns each $each to an element of the @newlist array. Finally, the for loop starting on line 14 simply steps through each element of both the @newlist and @list arrays simultaneously and subtracts one array from the other. You would expect the first iteration of the for loop to be 2-1 yielding "1", the next iteration to give 4-2 yielding "2", and so on. So what's the problem here?
The answer lies in the first statement of the foreach block, $each *= 2;. What happens is that the @list array gets aliased through the $each variable. What does this mean? It means that whatever you do to the $each variable in the foreach loop, you also do to the corresponding element of the @list array. So, for example, when $each is equals "3" and it gets multiplied by "2", the third element of @list gets multiplied by "2", too, setting it's value to "6". And there you have the reason why the output of this code is nothing but 5 zeroes!
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: NEWBIE Brain Teaser
by Ri-Del (Friar) on Apr 15, 2001 at 08:04 UTC | |
by nysus (Parson) on Apr 15, 2001 at 08:27 UTC | |
by merlyn (Sage) on Apr 15, 2001 at 08:29 UTC | |
by Ri-Del (Friar) on Apr 15, 2001 at 09:45 UTC | |
by tilly (Archbishop) on Apr 16, 2001 at 06:27 UTC | |
| |
by hiroki (Novice) on Apr 16, 2001 at 19:29 UTC | |
by tilly (Archbishop) on Apr 16, 2001 at 19:53 UTC |