in reply to foreach only for a section of a list

Another way, with pop and push:

my $last = pop @somewords; foreach my $core (@somewords) { print " $core;\n" } push @somewords,$last;

Update: it's useless to keep $last. See the improvement by johngg, in reply.

Replies are listed 'Best First'.
Re^2: foreach only for a section of a list
by johngg (Canon) on May 05, 2012 at 12:13 UTC

    You could use a do block to scope the existence of $last so that it isn't left lying around.

    knoppix@Microknoppix:~$ perl -Mstrict -wE ' > my @arr = qw{ one two three four }; > push @arr, do { my $last = pop @arr; say for @arr; $last }; > say qq{@arr};' one two three one two three four knoppix@Microknoppix:~$

    Cheers,

    JohnGG