Perl: if ( element in list )

后端 未结 10 554
栀梦
栀梦 2021-01-30 06:05

I\'m looking for presence of an element in a list.

In Python there is an in keyword and I would do something like:

if element in list:
            


        
10条回答
  •  情歌与酒
    2021-01-30 07:05

    List::MoreUtils

    On perl >= 5.10 the smart match operator is surely the easiest way, as many others have already said.

    On older versions of perl, I would instead suggest List::MoreUtils::any.

    List::MoreUtils is not a core module (some say it should be) but it's very popular and it's included in major perl distributions.

    It has the following advantages:

    • it returns true/false (as Python's in does) and not the value of the element, as List::Util::first does (which makes it hard to test, as noted above);
    • unlike grep, it stops at the first element which passes the test (perl's smart match operator short circuits as well);
    • it works with any perl version (well, >= 5.00503 at least).

    Here is an example which works with any searched (scalar) value, including undef:

    use List::MoreUtils qw(any);
    
    my $value = 'test'; # or any other scalar
    my @array = (1, 2, undef, 'test', 5, 6);
    
    no warnings 'uninitialized';
    
    if ( any { $_ eq $value } @array ) {
        print "$value present\n"
    }
    

    P.S.

    (In production code it's better to narrow the scope of no warnings 'uninitialized').

提交回复
热议问题