Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: foreach only for a section of a list

by johngg (Canon)
on May 04, 2012 at 20:39 UTC ( [id://968981]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2024-04-16 09:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found