如何检查数组中是否不存在要由foreach循环处理的元素?
的例子:
my @array = ("abc","def","ghi");
foreach my $i (@array) {
print "I am inside arrayn";
#####'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 arrayn";
}
我可以想到这样做的方法,但想知道我是否可以用一种简短的方式得到它,要么使用特定的关键字或函数。我是这么想的:
my $index = 0;
while ($index < scalar @array) {
##Do my functionality here
}
if ($index == scalar @array) {
print "Proceedn";
}
有多种方法可以达到预期的效果,一些是基于使用数组的$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";
}
检测何时处理的一种方法是在最后一个元素
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
用于数组中最后一个元素的索引。
还需要注意的是,它们都适用于数组,如果需要使用索引
,则非常有用。while (my ($i, $elem) = each @ary) {
# ...
say "Last element, $elem" if $i == $#ary;
}
然后一定要阅读文档,以了解each
的微妙之处。
取决于你想如何处理空数组:
for my $ele ( @array ) {
say $ele;
}
say "Proceed";
或
for my $ele ( @array ) {
say $ele;
}
if ( @array ) {
say "Proceeding beyond $array[-1]";
}