Perl: if ( element in list )

后端 未结 10 563
栀梦
栀梦 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 06:51

    If you plan to do this many times, you can trade-off space for lookup time:

    #!/usr/bin/perl
    
    use strict; use warnings;
    
    my @array = qw( one ten twenty one );
    my %lookup = map { $_ => undef } @array;
    
    for my $element ( qw( one two three ) ) {
        if ( exists $lookup{ $element }) {
            print "$element\n";
        }
    }
    

    assuming that the number of times the element appears in @array is not important and the contents of @array are simple scalars.

提交回复
热议问题