Hash parsing considered ugly
Jonathan Stowe
jns at gellyfish.com
Sun Feb 26 21:16:00 GMT 2006
On Sat, 2006-02-25 at 22:27, drkjam wrote:
> When I say :-
>
> use strict;
> use warnings;
> use Data::Dumper;
>
> my %h = (
> foo => 1,
> foo => 2,
> );
>
> print Dumper(\%h);
>
> Perl provides :-
>
> $VAR1 = {
> 'foo' => 2
> };
>
> Assuming there is an awful lot more items in the hash than shown here
> this could lead to unexpected results. Is there any way at all to get
> Perl to flag this with at least some form of warning? It can lead to
> some rather insidious bugs if you aren't paying attention.
If you want to have a hash that has this kind of behaviour then you
might want to consider a tied hash, you can do something likeL
package MyHash;
use base Tie::Hash;
use Carp;
sub STORE
{
my ( $self, $key, $value ) = @_;
if ( exists $self->{$key} )
{
carp "Key $key already exists";
}
$self->{$key} = $value;
}
sub TIEHASH
{
my ( $class ) = @_;
my $hash = bless {}, $class;
return $hash;
}
sub FIRSTKEY {};
package main;
my %foo;
tie %foo, 'MyHash';
%foo = ( bar => 1, foo => 2 );
$foo{bar} = 2;
Of course you will want to add some extra stuff to the tied class to
make the hash behave properly.
/J\
--
This e-mail is sponsored by http://www.integration-house.com/
More information about the london.pm
mailing list