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

I have a hash as shown in the example below. I also have a text file with many lines of misc text. I am looking for an efficient way to loop through the file searching for any line that contains any of the keys in the hash. When one is found, I need to get the value for that hash key. I'm sure there is a better way of doing this. What am I missing?
#!/usr/bin/perl use strict; use warnings; my %hash_name = ( "one" => 1, "two" => 2, "three" => 3, "four" => 4 ); open MYFILE, ('/me/out.txt'); foreach my $line (<MYFILE>){ next if grep {$_ !~ keys %hash_name} $line; # above line seems to work but how do I find the hash key that match +ed? # OR is there a better way to do this altogether? } close(MYFILE);

Replies are listed 'Best First'.
Re: Looping through a file to find a hash key
by 1nickt (Canon) on Mar 03, 2016 at 00:57 UTC

    Here's a very simple example showing how to use grep to do what you want (although that may not be the best way!):

    use strict; use warnings; use feature qw/ say /; my %hash_name = ( "one" => 1, "two" => 2, "three" => 3, "four" => 4 ); while ( my $line = <DATA> ) { chomp $line; say "Line $. : $hash_name{$_}" for grep { $line =~ /$_/ } sort key +s %hash_name; } __DATA__ This one has it. This doesn't. This one has two. Nothing here. Three times lucky. Can we get a foursome for tennis? Blerghh.
    Output:
    Line 1 : 1 Line 3 : 1 Line 3 : 2 Line 6 : 4

    Hope this helps!


    The way forward always starts with a minimal test.
Re: Looping through a file to find a hash key ( quotemeta)
by Anonymous Monk on Mar 03, 2016 at 00:19 UTC

    I'm sure there is a better way of doing this. What am I missing?

    add use re 'debug'; and you'll see that  keys %hash_name doesn't make a very good pattern.

    You can use  my $keys = join '|', map {"\Q$_\E"} keys %words; but simply iterating over the has might be faster