加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 捕捉“for loop到达最后一个元素”的优雅方式?

发布时间:2020-12-15 23:21:18 所属栏目:大数据 来源:网络整理
导读:有时在Perl中,我编写了一个for / foreach循环,它迭代值以检查列表中的值.在第一次击中之后,循环可以退出,因为我们已经满足了我的测试条件.例如,这个简单的代码: my @animals = qw/cat dog horse/;foreach my $animal (@animals){ if ($input eq $animal) {
有时在Perl中,我编写了一个for / foreach循环,它迭代值以检查列表中的值.在第一次击中之后,循环可以退出,因为我们已经满足了我的测试条件.例如,这个简单的代码:

my @animals = qw/cat dog horse/;

foreach my $animal (@animals)
{
  if ($input eq $animal)
  {
    print "Ah,yes,an $input is an animal!n";
    last;
  }
}
# <-----

是否有一种优雅的方式 – 可能是一个重载的关键字 – 来处理“for循环到达最后一个元素”?什么东西放在上面的箭头?

我可以想办法做到这一点,比如创建/设置一个额外的$found变量并在最后测试它……但是我希望Perl可能还有其他内置的东西,比如:

foreach my $animal (@animals)
{
  if ($input eq $animal)
  {
    print "Ah,an $input is an animal!n";
    last;
  }
} finally {
  print "Sorry,I'm not sure if $input is an animal or notn";
}

这将使这个测试更直观.

解决方法

您可以使用带标签的块包装循环,如下所示:

outer: {
    foreach my $animal (@animals) {
        if ($input eq $animal) {
            print "Ah,an $input is an animal!n";
            last outer;
        }
    }
    print "no animal foundn";
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读