How can I verify that a value is present in an array (list) in Perl?

前端 未结 8 972
生来不讨喜
生来不讨喜 2020-12-02 20:47

I have a list of possible values:

@a = qw(foo bar baz);

How do I check in a concise way that a value $val is present or absent

8条回答
  •  鱼传尺愫
    2020-12-02 21:38

    Use the first function from List::Util which comes as standard with Perl....

    use List::Util qw/first/;
    
    my @a = qw(foo bar baz);
    if ( first { $_ eq 'bar' } @a ) { say "Found bar!" }
    

    NB. first returns the first element it finds and so doesn't have to iterate through the complete list (which is what grep will do).

提交回复
热议问题