How can I search for a fixed and string insensitive string pattern in an array in Perl?

I want to make a perl script to take a list of values ​​(keys in a hash) and search through an array. I need to look for a fixed pattern, but it might be case insensitive. This is my code:

foreach my $element ( keys %data ) {
    # this line search the exact pattern, but it isn't case insensitive
    if ( first { $element eq $_ } @database_lines ) {
        $counter += 1;
        print "$element\n";
    } else {
        next;
    }
}

      

Some ideas? Thanks in advance.

+3


source to share


3 answers


I would probably create a hash of @database_lines

the bottom- skinned content and then look at this:

my %db_lines;
$db_lines{lc $_} = 1 for @database_lines;

foreach my $element (keys %data) {
    if ($db_lines{lc $element}) {
        $counter++;
        print "$element\n";
    }
}

      



If your Perl is new enough, you can use fc instead of lc to provide a more accurate case-sensitive match.

+2


source


This will check the use of the "contains" condition:

@f = grep /\Q$element\E/i, @lines;
print $f[0];

      



If you want an exact match, use:

@f = grep /^\Q$element\E\z/i, @lines;
print $f[0];

      

+1


source


I would recommend doing this task this way

use v5.16;
my $count = do {
    my %hash;
    @hash{map fc, @database_lines} = ();
    grep exists $hash{fc($_)}, keys %data;
};

      

The advantage is that this code is O(M+N)

instead of O(M*N)

your original approach.

0


source







All Articles