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

后端 未结 7 1680
一向
一向 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:27

    If you will be doing many searches of the array, AND matching always is defined as string equivalence, then you can normalize your data and use a hash.

    my @strings = qw( aAa Bbb cCC DDD eee );
    
    my %string_lut;
    
    # Init via slice:
    @string_lut{ map uc, @strings } = ();
    
    # or use a for loop:
    #    for my $string ( @strings ) {
    #        $string_lut{ uc($string) } = undef;
    #    }
    
    
    #Look for a string:
    
    my $search = 'AAa';
    
    print "'$string' ", 
        ( exists $string_lut{ uc $string ? "IS" : "is NOT" ),
        " in the array\n";
    

    Let me emphasize that doing a hash lookup is good if you are planning on doing many lookups on the array. Also, it will only work if matching means that $foo eq $bar, or other requirements that can be met through normalization (like case insensitivity).

    0 讨论(0)
提交回复
热议问题