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

134,641

Solution 1

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

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

Solution 2

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

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.

Share:
134,641
Admin
Author by

Admin

Updated on March 08, 2020

Comments

  • Admin
    Admin over 4 years

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