Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

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 ( [id://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.


Dave

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-04-24 11:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found