Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
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 avoiding work at the Monastery: (3)
As of 2026-01-20 03:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (124 votes). Check out past polls.

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.