Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: For vs. While

by ikegami (Patriarch)
on Dec 05, 2006 at 23:57 UTC ( [id://588007]=note: print w/replies, xml ) Need Help??


in reply to For vs. While

for (@array) loops until the number of iterations is greater than the number of elements in the array. When you reached the 3rd iteration of your for loop, @_ only has two elements (because of shift and pop), so the loop exits.

sub f1 { while (@_) { print(shift); } print("\n"); } sub f2 { for (@_) { print(shift); } print("\n"); } sub f3 { for (map $_, @_) { print(shift); } print("\n"); } f1(map/./g, Japh); # Japh f2(map/./g, Japh); # Ja f3(map/./g, Japh); # Japh

f2 iterates over the elements of @_.
f3 iterates over a premade list on the stack, so it doesn't matter that @_ changes.

Replies are listed 'Best First'.
Re^2: For vs. While
by Andrew_Levenson (Hermit) on Dec 06, 2006 at 00:54 UTC
    Ahh, that makes perfect sense. Thanks!
    V(qw/74 401 211 79/);sub V{while(@_){$v**=$V?$#_:$V; print(map{$V<$v?chr(shift):chr(reverse(pop))}$_),$V+=$#_%2!=1?1:0}}

      That behaviour is specifically for for (@array). for (@array) is different than other forms of for (LIST). As soon as one iterates over anything but just an array, it's the size of the list on the stack that matters.

      The real difference is that for (@array) is optimized to avoid flattening @array onto the stack. Instead, for (@array) navigates @array in place. For all other expressions, a list is formed on the stack and for iterates over that.

      The following show the difference between iterating in place, and iterating over a list on the stack.

      sub f4 { for (@_) { print($_); shift; } print("\n"); } sub f5 { for ((), @_) { print($_); shift; } print("\n"); } f4(map/./g, Japh); # Jp f5(map/./g, Japh); # Japh

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://588007]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-03-29 07:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found