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

后端 未结 5 1594
刺人心
刺人心 2020-12-15 15:01

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 has

相关标签:
5条回答
  • 2020-12-15 15:33

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

    if (exists $strings{$string}) {
        ...
    } else {
        ...
    }
    
    0 讨论(0)
  • 2020-12-15 15:34

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-15 15:48

    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.

    0 讨论(0)
  • 2020-12-15 15:49

    You can just go with:

    if(!$strings{$string}) ....
    
    0 讨论(0)
提交回复
热议问题