http://qs321.pair.com?node_id=11140746


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