Perl:仅当数组的foreach循环没有要处理的元素时才进行进一步处理(foreach循环的最后一次迭代处于打开状态)

xa9qqrwz  于 2022-11-15  发布在  Perl
关注(0)|答案(3)|浏览(148)

如何检查数组中是否不存在要由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";
}
cld4siwp

cld4siwp1#

有多种方法可以获得所需的结果,一些方法基于使用数组的$index,而另一些方法基于使用$#array-1$#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";
}
ymdaylpp

ymdaylpp2#

一种检测何时在最后一个元素处进行处理的方法

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用于数组中最后一个元素的索引。
还要注意,each适用于数组,这在使用索引时很有用

while (my ($i, $elem) = each @ary) { 
    # ...
    say "Last element, $elem" if $i == $#ary;
}

然后一定要阅读文档,以了解each的微妙之处。

afdcj2ne

afdcj2ne3#

根据您要行程空数组的方式:

for my $ele ( @array ) {
    say $ele;
}

say "Proceed";

for my $ele ( @array ) {
    say $ele;
}

if ( @array ) {
   say "Proceeding beyond $array[-1]";
}

相关问题