I am building a hash where the keys, associated with scalars, are not necessarily unique. 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?