Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Test for the last element in a foreach

by wind (Priest)
on Aug 03, 2007 at 00:39 UTC ( [id://630425]=note: print w/replies, xml ) Need Help??


in reply to Test for the last element in a foreach

If you care about the position of elements in an array, you should simply iterate them by index instead of by element.
my @children = $category->children; for my $i (0..$#children) { my $subcat = $children[$i]; my $is_last = $i == $#children; # More code here. }
There is nothing particularly elegant or fancy about this solution. In fact, it's down right boring. However, it's very clear what purpose each variable serves. And so is very maintainable.

There are other abstractions that you could use that are more both elegant or obfuscated. One good way would be to use an Iterator class. However, this needlessly adds more dependencies to something that is honestly very basic, so I at least wouldn't bother.

- Miller

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://630425]
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: (1)
As of 2026-01-18 07:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your view on AI coding assistants?





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