alagurocks has asked for the wisdom of the Perl Monks concerning the following question:

Hope someone can help me with this. I have a file which has a list of lines. I want to see if those lines exist in a hash. The lines in the file may have wildcards to match multiple entries in the hash. Assume that $var1 is a line from my file. I want the last line in this code to print out a YES I do know that $var1 is not ready(after the current substitutions as shown) for checking if it exists in the hash with this code below.I just want to know how to do it.

my %data = (); $data{b_slash_car_bit_slash_tebla_bit} = b/car[10]/tebla[9] $data{b_slash_car_bit_slash_tesla_bit } = b/car[10]/tesla[0] b/car[9]. +tesla[1]; my $var1 = "b/car[*]/te*a"; $var1 =~ s/\//_slash_/g; $var1 =~ s/\[\*\]/\_bit_/g; if (defined $data{$var1}) {print "YES";} else {print "No";}

Replies are listed 'Best First'.
Re: Pattern match and fish out a entry from a hash
by Kenosis (Priest) on Jul 02, 2012 at 19:28 UTC

    If I understand your issue correctly, perhaps the following will generate what you need:

    use Modern::Perl; my %data = (); $data{b_slash_car_bit_slash_tebla_bit} = 'b/car[10]/tebla[9]'; $data{b_slash_car_bit_slash_tesla_bit} = 'b/car[10]/tesla[0] b/car[9]. +tesla[1]'; $data{b_slash_car_bit_slash_tisla_bit} = 'b/car[10]/tesla[0] b/car[9]. +tesla[1]'; my $var1 = 'b/car[*]/te.*a'; # <-- changed this to .* $var1 =~ s/\//_slash_/g; $var1 =~ s/\[\*\]/\_bit/g; # <-- changed _bit_ to _bit say /$var1/ ? 'YES' : 'NO' for keys %data;

    Output:

    YES YES NO

    Each key of the hash is checked in the ternary statement for the pattern contained in $var1, resulting in printing "YES" if found, else "NO."

    Hope this helps!