Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"

Re: Perl's feature to determine, in current point of loop, that this is the last one?

by davido (Cardinal)
on Jan 23, 2022 at 19:06 UTC ( #11140746=note: print w/replies, xml ) Need Help??

in reply to Perl's feature to determine, in current point of loop, that this is the last one?

There's no general solution for all types of loops and all data the loops may be iterating over. Could you explain what your data source is, and whether you're using a for/foreach loop, a while loop, or something else? I assume you're using a loop that looks like:

foreach my $element (@array) {...

But that could be a mistaken assumption. Also, how different does that last element need to be treated? What populated the array, and what will you be doing with it afterwards?

This is probably a terrible idea but you could bless a reference to the last element and detect that blessing:

my @array = qw(a b c d e f g); { local $array[-1] = $array[-1]; bless \$array[-1], 'last'; foreach my $element (@array) { if (ref(\$element) eq 'last') { print "This is the last element: "; } print "$element\n"; } }

The straightforward approach of just counting elements is less opaque. And if you're going to do that, a C style loop is probably the logical conclusion. However, if we knew more about where the data is coming from and what is really needed we may be able to provide a more on-target solution.


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2022-05-23 11:57 GMT
Find Nodes?
    Voting Booth?
    Do you prefer to work remotely?

    Results (82 votes). Check out past polls.