Output:use strict; use warnings; my @list = 'a'..'z'; for my $letter (@list) { my $popped = pop @list; printf "letter: %s popped: %s list: %s\n",$letter,$popped,join('', +@list); }
By the time you reach letter 'm' you have removed enough items from the end of the list that you are now at the new end.letter: a popped: z list: abcdefghijklmnopqrstuvwxy letter: b popped: y list: abcdefghijklmnopqrstuvwx letter: c popped: x list: abcdefghijklmnopqrstuvw letter: d popped: w list: abcdefghijklmnopqrstuv letter: e popped: v list: abcdefghijklmnopqrstu letter: f popped: u list: abcdefghijklmnopqrst letter: g popped: t list: abcdefghijklmnopqrs letter: h popped: s list: abcdefghijklmnopqr letter: i popped: r list: abcdefghijklmnopq letter: j popped: q list: abcdefghijklmnop letter: k popped: p list: abcdefghijklmno letter: l popped: o list: abcdefghijklmn letter: m popped: n list: abcdefghijklm
Update - added quote from perlsyn
If any part of LIST is an array, "foreach" will get very confused if you add or remove elements within the loop body, for example with "splice". So don't do that
In reply to Re: Using Push and Pop. - response to update
by imp
in thread Using Push and Pop.
by dark314
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |