How do I search a Perl array for a matching string?

后端 未结 7 1704
一向
一向 2020-12-04 15:37

What is the smartest way of searching through an array of strings for a matching string in Perl?

One caveat, I would like the search to be case-insensitive

s

7条回答
  •  甜味超标
    2020-12-04 16:20

    Perl 5.10+ contains the 'smart-match' operator ~~, which returns true if a certain element is contained in an array or hash, and false if it doesn't (see perlfaq4):

    The nice thing is that it also supports regexes, meaning that your case-insensitive requirement can easily be taken care of:

    use strict;
    use warnings;
    use 5.010;
    
    my @array  = qw/aaa bbb/;
    my $wanted = 'aAa';
    
    say "'$wanted' matches!" if /$wanted/i ~~ @array;   # Prints "'aAa' matches!"
    

提交回复
热议问题