in reply to arrays: shifting in while loop

This is how Perl is interpreting the critical line of your code:

C:\test>perl -MO=Deparse,p -e" print (shift @a), (shift @a), "\n";" print(shift @a), shift @a, \'n'; -e syntax OK

As you can see, only the first parameter is being passed to print.

If you add another set of parens:

print( (shift @a), (shift @a), "\n" );

Or drop the parens entirely:

print shift @a, shift @a, "\n";

Your code will (probably) work as you expect.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

The start of some sanity?

Replies are listed 'Best First'.
Re^2: arrays: shifting in while loop
by ivanthemad (Initiate) on Mar 06, 2012 at 14:47 UTC
    Thank you, you are correct! Re-examining my code in the interim between posting and your timely response, I noticed that I was in fact receiving a warning:
    print (...) interpreted as function at - line 7.
    Thank you for the clear explanation which has rectified my misunderstanding! I will also examine further your use of -MO=Deparse,p -e, which looks to be very useful indeed.

      When you get a message like "print (...) interpreted as function ...", you can typically disambiguate your statement for Perl by simply adding a + in front of the opening parenthesis.

      Your original code runs like this:

      ken@ganymede: ~/local/bin $ perl -Mstrict -Mwarnings -E 'my $s = "foo bar baz qux 3 3 1 3"; my @ +a = split /\s/, $s; splice(@a, 0, 4); while (@a) { print (shift @a), +(shift @a), "\n"; }' print (...) interpreted as function at -e line 1. Useless use of a constant ( ) in void context at -e line 1. 31ken@ganymede: ~/local/bin $

      Adding a single + (changing ... print (... to ... print +(...), you get the output you were after:

      ken@ganymede: ~/local/bin $ perl -Mstrict -Mwarnings -E 'my $s = "foo bar baz qux 3 3 1 3"; my @ +a = split /\s/, $s; splice(@a, 0, 4); while (@a) { print +(shift @a), + (shift @a), "\n"; }' 33 13 ken@ganymede: ~/local/bin $

      This is discussed in more detail in perlop - Symbolic Unary Operators.

      -- Ken

      Do note you only get said warning because you use exactly one space between print and the parenthesis. Drop the space, use 2 spaces, or a tab, and the warning disappears. Replace print by warn, and the warning disappears as well.