in reply to Throw compilation error(or warning) if duplicate keys are present in hash

There is no way that I know of to tell Perl that assigning a different value to a hash key is an error. That is because that is defined in the language to be completely ok!

If you want checking like that, then the way to do it is to read the data like it came from an external file, build the hash and report errors as the data is processed.

There are many formulations of how to do this. I present one below.

#!/usr/bin/perl -w use strict; use Data::Dumper; my $hash_data = <<END; #this is a "here is" string one 1 two 2 one 3 END my %seen; my %hash = map{ my ($text, $number) = split; warn "\"$text\" has been re-defined!\n" if $seen{$text}++; ($text,$number); }split (/\n/, $hash_data); print Dumper \%hash; __END__ Prints: "one" has been re-defined! $VAR1 = { 'one' => '3', 'two' => '2' };
  • Comment on Re: Throw compilation error(or warning) if duplicate keys are present in hash
  • Download Code

Replies are listed 'Best First'.
Re^2: Throw compilation error(or warning) if duplicate keys are present in hash
by I_love_perl (Novice) on Nov 24, 2011 at 11:53 UTC

    Hi Marshall,

    Thanks for your response.

    You are right in saying that the re-definition of a key with a new value is perfectly fine.

    But this leads to a anomaly called RD (Re-Definition). The RD means re-defining a variable with a new value without using it's initial value (They say to use your later value as initial one than initializing the variable to something else and changing the variable's value without using it's initial value). The coding guide lines say to identify such cases and rectify the same.

    This is one of the reason why I'm thinking of getting a warning or error from standard perl or any of it's additional packages (like use strict,warnings)