如何檢查陣列中是否不存在要由 foreach 回圈處理的元素?
例子:
my @array = ("abc","def","ghi");
foreach my $i (@array) {
print "I am inside array\n";
#####'Now, I want it further to go if there are no elements after
#####(or it can be said if it is the last element of array. Otherwise, go to next iteration'
print "i did this because there is no elements afterwards in array\n";
}
我可以想辦法做到這一點,但想知道我是否可以使用特定的關鍵字或函式以簡短的方式獲得它。我想的一種方式:
my $index = 0;
while ($index < scalar @array) {
##Do my functionality here
}
if ($index == scalar @array) {
print "Proceed\n";
}
uj5u.com熱心網友回復:
有多種方法可以實作所需的結果,一些基于$index陣列的使用,另一些基于$#array-1可用于獲取陣列切片的使用,陣列的最后一個元素可通過$array[-1].
use strict;
use warnings;
use feature 'say';
my @array = ("abc","def","ghi");
say "
Variation #1
-------------------";
my $index = 0;
for (@array) {
say $index < $#array
? "\$array[$index] = $array[$index]"
: "Last one: \$array[$index] = $array[$index]";
$index ;
}
say "
Variation #2
-------------------";
$index = 0;
for (@array) {
unless ( $index == $#array ) {
say "\$array[$index] = $_";
} else {
say "Last one: \$array[$index] = $_";
}
$index ;
}
say "
Variation #3
-------------------";
$index = 0;
for( 0..$#array-1 ) {
say "\$array[$index] = $_";
$index ;
}
say "Last one: \$array[$index] = $array[$index]";
say "
Variation #4
-------------------";
for( 0..$#array-1 ) {
say $array[$_];
}
say 'Last one: ' . $array[-1];
say "
Variation #5
-------------------";
my $e;
while( ($e,@array) = @array ) {
say @array ? "element: $e" : "Last element: $e";
}
uj5u.com熱心網友回復:
一種檢測何時處理在最后一個元素的方法
my @ary = qw(abc def ghi);
foreach my $i (0..$#ary) {
my $elem = $ary[$i];
# work with $elem ...
say "Last element, $elem" if $i == $#ary;
}
語法$#array-name用于陣列中最后一個元素的索引。
uj5u.com熱心網友回復:
取決于您要如何處理空陣列:
for my $ele ( @array ) {
say $ele;
}
say "Proceed";
或者
for my $ele ( @array ) {
say $ele;
}
if ( @array ) {
say "Proceeding beyond $array[-1]";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/498060.html
下一篇:二維陣列列印作為參考
