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;
}
}
}
I believe to check if a key exists in a hash you just do
if (exists $strings{$string}) {
...
} else {
...
}