【问题标题】:How to check whether variable is in list? [duplicate]如何检查变量是否在列表中? [复制]
【发布时间】:2017-01-27 21:07:59
【问题描述】:

有没有办法在perl 中做这样的事情?

$str = "A"
print "Yes" if $str in ('A','B','C','D');

【问题讨论】:

  • smartmatch ~~ 但它是实验性的。
  • 有没有办法使用匿名数组或者你必须按照我在回答中所做的那样做?
  • @CJ7:不相关,但我注意到您提出的大多数问题都处于开放状态。请接受这些问题的答案以关闭它们(假设您对答案感到满意)。谢谢。另见:meta.stackexchange.com/questions/5234/…
  • 我作为骗子关闭了它。请参阅 Ether 的 comprehensive answer

标签: list perl set


【解决方案1】:
$str = "A";
@arr = ('A','B','C','D');
print "Yes" if $str ~~ @arr;

【讨论】:

  • print "Yes" if 'A' ~~ ['A','B','C','D']; 也可以,但使用 smartmatch 可能不是最好的主意。
【解决方案2】:

智能匹配是experimental,将在未来的版本中更改或消失。您将在 Perl 5.18+ 版本中收到相同的警告。以下是替代方案:

使用 grep

#!/usr/bin/perl
use strict;
use warnings;
my $str = "A";
print "Yes" if grep {$_ eq 'A'} qw(A B C D);

使用任何

#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw(any);
print any { $_ eq 'A' } qw(A B C D);

使用哈希

#!/usr/bin/perl
use strict;
use warnings;
my @array = qw(A B C D);
my %hash = map { $_ => 1 } @array;
foreach my $search (qw(A)) #enter list items to be searched here
{
   print exists $hash{$search};
}

另见:

  • match::smart - 提供匹配运算符 |M|它的行为或多或少与(从 Perl 5.18 开始)实验性智能匹配运算符相同。
  • Syntax::Feature::Junction - 为任何、全部、无或一个提供关键字
  • 您也可以使用List::Util::first,它会更快,因为它会在找到匹配项时停止迭代。

【讨论】:

  • 我正在使用 perl v5.16.3,但没有收到任何警告。
  • 因为它在 5.18+ 版本中已被弃用。
  • List::Util::first 和 List::Util::any 都在找到匹配项后立即停止迭代,所以我不确定您为什么提供 first 作为替代方案。 first 还要求您检查 undef 是否有任何列表元素可能是虚假的:say "match" if defined first { ... } @array 与简单的 say "match" if any { ... } @array
【解决方案3】:

您可以将数组转换为哈希。然后您可以有效地(在恒定时间内,或 O(1))检查您的字符串是否在原始数组中。以下是关于如何查找字符串'C' 的两种不同方法:

#!/usr/bin/perl
use strict;
use warnings;

my %hash1 = map {$_ => 0} qw/A B C D/;
print 'Yes' if exists $hash1{'C'};

#!/usr/bin/perl
use strict;
use warnings;

my %hash2;
@hash2{qw/A B C D/} = ();
print 'Yes' if exists $hash2{'C'};

当然,就像在 Perl 中一样,TIMTOWTDI。

【讨论】:

    猜你喜欢
    • 2011-05-20
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 2020-10-21
    • 2016-01-28
    相关资源
    最近更新 更多