Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Test for the last element in a foreach

by CountZero (Bishop)
on Aug 02, 2007 at 20:30 UTC ( [id://630391]=note: print w/replies, xml ) Need Help??


in reply to Test for the last element in a foreach

I was thinking of:
my @array = (1 .. 10); my $counter; foreach my $element (@array) { print "Last element follows now!\n" if ++$counter == scalar(@ar +ray); print "$element\n"; }

Output:

1 2 3 4 5 6 7 8 9 Last element follows now! 10

You can leave out the scalar function but then you have to take care that the test does not get evaluated in list context.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2026-01-21 16:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





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