繁体   English   中英

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

[英]Perl: Go to further processing only if there are no elements to be processed by foreach loop of array (last iteration of foreach loop is on)

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

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

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用于数组中最后一个元素的索引。

有多种方法可以达到预期的结果,一些基于数组$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";
}

取决于您要如何处理空数组:

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

say "Proceed";

或者

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM