Perl::Critic::Policy::ValuesAndExpressions::ProhibitDuplicateHashKeys3pm
Disallow duplicate literal hash keys
Overview
This policy is part of the "Perl::Critic::Pulp" add-on. It reports duplicate literal hash keys in a hash assignment or anonymous hashref.
my %hash = (red => 1,green => 2,red => 3, # bad);my $hashref = { red => 1,red => 3, # bad};
Writing duplicate literal keys is probably a mistake or too much cut and paste, and if the values are different will make it unclear to human readers what was meant. On that basis this policy is under the "bugs" theme and medium severity (see "POLICY THEMES" in Perl::Critic).
Perl is happy to run code like the above. The value of the last "red" is stored. As runtime behaviour, this is good since you can give defaults which further values from a caller or similar can replace. For example,
sub new {my $class = shift;return bless { foo => 'default',bar => 'default',@_ }, $class;}MyClass->new (foo => 'caller value'); # overriding 'default'
Expressions
Expressions within a hash list cannot be checked in general. Some concatenations of literals are recognised though they're probably unusual.
my %hash = (ab => 1,'a'.'b' => 2); # badmy %hash = (__PACKAGE__.'a' => 1,__PACKAGE__.'a' => 2); # bad
Function calls etc within a list might return an odd or even number of values. Fat commas "=>" are taken as indicating a key when in doubt.
my %hash = (blah() => 1, # guided by =>a => 2,a => 3); # badmy %hash = (blah(),a => 2, # guided by =>a => 3); # bad
A hash substitution is always an even number of arguments,
my %hash = (a => 1,%blah, # even numbera => 5); # bad, duplicate
"qw()" words are recognised too
my %hash = (qw(foo value1foo value2)); # bad
Disabling
If you don't care about this you can always disable "ProhibitDuplicateHashKeys" from your .perlcriticrc file in the usual way (see "CONFIGURATION" in Perl::Critic),
[-ValuesAndExpressions::ProhibitDuplicateHashKeys]
Home page
http://user42.tuxfamily.org/perl-critic-pulp/index.html
Releases
4 releases since Debian 10 (Buster); the text changed 1 time.