I have one array which I am checking for values in a hash (which I created). The idea is to check each element of the array if exists in the hash keys. If it does not exists, it should say that the non-existent element appears zero times. The hash I created to count frequency of numbers on a second array.
Here's what I did:
use strict;
use warnings;
sub main {
my @Source = ("A", "B", "D");
my @ArrToHash = ("A", "C", "A", "B", "E", "F");
my %hashy;
++$hashy{$_} for @ArrToHash;
foreach my $e (@Source) {
if (exists $hashy{$e}) {
print "$e are $hashy{$e}\n";
}
}
}
main();
I am getting
A are 2
B are 1
While in reality I would like:
A are 2
B are 1
D are 0
Any clue? How to fix my code?
if (exists $hashy{$e}) {
print "$e are $hashy{$e}\n";
}else{
print "$e are 0\n";
}
OR
printf "%s are %d\n", $e, $hashy{$e} // 0 ;
Comment:
I prefer $hashy{$e} // 0
. It returns $hashy{$e}
if $hashy{$e}
exits and it is not undef.
Ikegami prefers $hashy{$e} || 0
. It returns 0
also when $hashy{$e}
is an empty string. It works with older perl versions without //
operator support.
IMHO It is a matter of "style-guide" in most situations.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加