in reply to Test for the last element in a foreach
Since you said "array", you can use \$_ == \$array[-1]:
my @array= ( 1..5 ); for( @array ) { if( \$_ == \$array[-1] ) { print "Last element.\n"; } print $_, $/; } __END__ 1 2 3 4 Last element. 5
Update: ikegami asked about Data::Alias being able to confuse this test. Yes, that can be done, and one can even do it w/o such a module but it requires some unusual contortions and so probably isn't something to worry too much about:
my $five= 5; *array= sub { \@_ }->( 1, 2, $five, 4, $five ); for( @array ) { if( \$_ == \$array[-1] ) { print "Last element.\n"; } print $_, $/; } __END__ 1 2 Last element. 5 4 Last element. 5
- tye
|
|---|