Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Throw compilation error(or warning) if duplicate keys are present in hash

by afoken (Chancellor)
on Nov 24, 2011 at 12:57 UTC ( [id://939874]=note: print w/replies, xml ) Need Help??


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

What about tie?

#!/usr/bin/perl { package AssignOnce; use strict; use warnings; use Carp (); use Tie::Hash; use parent -norequire => 'Tie::StdHash'; # why, oh why, is Tie::St +dHash hidden in Tie::Hash? sub STORE { my ($self,$key,$value)=@_; if (exists $self->{$key}) { Carp::carp("Overwriting hash key '$key', old value: '$self +->{$key}', new value: '$value'"); } $self->SUPER::STORE($key,$value); } } use strict; use warnings; use Data::Dumper; our %h; tie %h,'AssignOnce'; %h=( one => 1, two => 2, one => 3, ); print Dumper(\%h);

Result:

Overwriting hash key 'one', old value: '1', new value: '3' at tie.pl l +ine 29 $VAR1 = { 'one' => 3, 'two' => 2 };

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://939874]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2024-04-19 11:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found