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

后端 未结 7 1703
一向
一向 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:23

    For just a boolean match result or for a count of occurrences, you could use:

    use 5.014; use strict; use warnings;
    my @foo=('hello', 'world', 'foo', 'bar', 'hello world', 'HeLlo');
    my $patterns=join(',',@foo);
    for my $str (qw(quux world hello hEllO)) {
        my $count=map {m/^$str$/i} @foo;
        if ($count) {
            print "I found '$str' $count time(s) in '$patterns'\n";
        } else {
            print "I could not find '$str' in the pattern list\n"
        };
    }
    

    Output:

    I could not find 'quux' in the pattern list
    I found 'world' 1 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
    I found 'hello' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
    I found 'hEllO' 2 time(s) in 'hello,world,foo,bar,hello world,HeLlo'
    

    Does not require to use a module.
    Of course it's less "expandable" and versatile as some code above.
    I use this for interactive user answers to match against a predefined set of case unsensitive answers.

提交回复
热议问题