Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
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 examining the Monastery: (2)
As of 2025-03-17 04:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When you first encountered Perl, which feature amazed you the most?










    Results (54 votes). Check out past polls.