How can I see if a Perl hash already has a certain key?

PerlHashKeyLookup

Perl Problem Overview


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;
        }
    }
}

Perl Solutions


Solution 1 - Perl

I believe to check if a key exists in a hash you just do

if (exists $strings{$string}) {
    ...
} else {
    ...
}

Solution 2 - Perl

I would counsel against using if ($hash{$key}) since it will not do what you expect if the key exists but its value is zero or empty.

Solution 3 - Perl

Well, your whole code can be limited to:

foreach $line (@lines){
        $strings{$1}++ if $line =~ m|my regex|;
}

If the value is not there, ++ operator will assume it to be 0 (and then increment to 1). If it is already there - it will simply be incremented.

Solution 4 - Perl

I guess that this code should answer your question:

use strict;
use warnings;

my @keys = qw/one two three two/;
my %hash;
for my $key (@keys)
{
    $hash{$key}++;
}

for my $key (keys %hash)
{
   print "$key: ", $hash{$key}, "\n";
}

Output:

three: 1
one: 1
two: 2

The iteration can be simplified to:

$hash{$_}++ for (@keys);

(See $_ in perlvar.) And you can even write something like this:

$hash{$_}++ or print "Found new value: $_.\n" for (@keys);

Which reports each key the first time it’s found.

Solution 5 - Perl

You can just go with:

if(!$strings{$string}) ....

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser105574View Question on Stackoverflow
Solution 1 - PerlcpjolicoeurView Answer on Stackoverflow
Solution 2 - PerlRETView Answer on Stackoverflow
Solution 3 - Perluser80168View Answer on Stackoverflow
Solution 4 - PerlzoulView Answer on Stackoverflow
Solution 5 - PerlAJ.View Answer on Stackoverflow