Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Test for the last element in a foreach (==\)

by tye (Sage)
on Aug 02, 2007 at 20:16 UTC ( [id://630384]=note: print w/replies, xml ) Need Help??


in reply to Test for the last element in a foreach

Since you said "array", you can use \$_ == \$array[-1]:

my @array= ( 1..5 ); for( @array ) { if( \$_ == \$array[-1] ) { print "Last element.\n"; } print $_, $/; } __END__ 1 2 3 4 Last element. 5

Update: ikegami asked about Data::Alias being able to confuse this test. Yes, that can be done, and one can even do it w/o such a module but it requires some unusual contortions and so probably isn't something to worry too much about:

my $five= 5; *array= sub { \@_ }->( 1, 2, $five, 4, $five ); for( @array ) { if( \$_ == \$array[-1] ) { print "Last element.\n"; } print $_, $/; } __END__ 1 2 Last element. 5 4 Last element. 5

- tye        

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (2)
As of 2026-01-24 18:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





    Results (126 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.