Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Comment on

Now that the cat's out of the bag, I'll share the explanation I had written up...a bit more long winded:


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!

In reply to Re: NEWBIE Brain Teaser by nysus
in thread NEWBIE Brain Teaser by nysus

and:  <code> code here </code>

  • Please read these before you post! —
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others contemplating the Monastery: (5)
    As of 2014-12-27 10:38 GMT
    Find Nodes?
      Voting Booth?

      Is guessing a good strategy for surviving in the IT business?

      Results (177 votes), past polls