Cleaner way to store to replace a scalar hash value with an array ref?

Posted by user275455 on Stack Overflow See other posts from Stack Overflow or by user275455
Published on 2010-04-08T15:30:16Z Indexed on 2010/04/08 15:33 UTC
Read the original article Hit count: 155

Filed under:
|

I am building a hash where the keys, associated with scalars, are not necessarily unique. I want the desired behavior to be that if the key is unique, the value is the scalar. If the key is not unique, I want the value to be an array reference of the scalars associated witht the key. Since the hash is built up iteratively, I don't know if the key is unique ahead of time. Right now, I am doing something like this:

if(!defined($hash{$key})){ $hash{$key} = $val; } elseif(ref($hash{$key}) ne 'ARRAY'){ my @a; push(@a, $hash{$key}); push(@, $val); $hash{$key} = \@a; } else{ push(@{$hash{$key}}, $val); }

Is there a simpler way to do this?

© Stack Overflow or respective owner

Related posts about perl

Related posts about hash