Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Test for the last element in a foreach

by almut (Canon)
on Aug 02, 2007 at 20:21 UTC ( [id://630387]=note: print w/replies, xml ) Need Help??


in reply to Test for the last element in a foreach

Yet another variant:

my @elems = qw(a b c d e); my $n = $#elems; for my $elem (@elems) { print "last elem = $elem\n" if !$n--; }

Update: as to your updated question: if you want to avoid creating a named array at any price, you could do something like this (but I'm not sure if I should seriously recommend that...)

my $n; for my $elem (map {$n++; $_} qw(a b c d e)) { print "last elem = $elem\n" if !--$n; }

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (3)
As of 2025-03-27 01:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When you first encountered Perl, which feature amazed you the most?










    Results (69 votes). Check out past polls.

    Notices?
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.