How can I see if a Perl hash already has a certain key?
hash, key, lookup, perl
Solution
I believe to check if a key exists in a hash you just do
if (exists $strings{$string}) {
...
} else {
...
}
Problem
I have a Perl script that is counting the number of occurrences of various strings in a text file. I want to be able to check if a certain string is not yet a key in the hash. Is there a better way of doing this altogether? Here is what I am doing: ``` foreach $line (@lines){ if(($line =~ m|my regex|) ) { $string = $1; if ($string is not a key in %strings) # "strings" is an associative array { $strings{$string} = 1; } else { $n = ($strings{$string}); $strings{$string} = $n +1; } } } ```