in reply to foreach only for a section of a list

An interesting selection of approaches in this thread, here's a variation on slicing.

knoppix@Microknoppix:~$ perl -E ' > @arr = qw{ one two three four }; > say for do { local @arr = @arr[ 0 .. $#arr - 1 ]; @arr }; > say qq{@arr};' one two three one two three four knoppix@Microknoppix:~$

Update: You can't localise a lexical variable so, if running under strictures you would have to declare @arr with our to make it a package variable or make it a lexical with my and declare a new lexical inside the do block.

knoppix@Microknoppix:~$ perl -Mstrict -wE ' > our @arr = qw{ one two three four }; > say for do { local @arr = @arr[ 0 .. $#arr - 1 ]; @arr}; > say qq{@arr};' one two three one two three four knoppix@Microknoppix:~$
knoppix@Microknoppix:~$ perl -Mstrict -wE ' > my @arr = qw{ one two three four }; > say for do { my @arr = @arr[ 0 .. $#arr - 1 ]; @arr}; > say qq{@arr};' one two three one two three four knoppix@Microknoppix:~$

Cheers,

JohnGG

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

    I don't get it. Instead of
        say for do { my @arr = @arr[ 0 .. $#arr - 1 ]; @arr};
    et al, why not just
        say for do { @arr[ 0 .. $#arr-1 ] };
    or (much) better yet...

    >perl -wMstrict -lE "my @arr = qw{ one two three four }; say for @arr[ 0 .. $#arr-1 ]; say qq{@arr}; " one two three one two three four