in reply to Converting a hash element into an array

use strict; use warnings; sub getHash { my %hash; for(my $i=0;$i<4;$i++) { my $key = <STDIN>; chomp($key); my $val = <STDIN>; chomp($val); if ( !defined $hash{$key} ) #first time { $hash{$key} = $val; } else { $hash{key} = ref($hash{key}) ? [ @{$hash{key}}, $val ] : [ $ha +sh{key}, $val ]; } } }
This leaves you however with the ambuigity of deciding wether there is an arrayref or a scalar under the keys of your hash in any code that processes the hash later on. It might be simpler to always use an arrayref, even when there's only a sngle element.
use strict; use warnings; sub getHash { my %hash; for(my $i=0;$i<4;$i++) { my $key = <STDIN>; chomp($key); my $val = <STDIN>; chomp($val); push @{$hash{key}}, $val; } }


holli, /regexed monk/

Replies are listed 'Best First'.
Re^2: Converting a hash element into an array
by rockers (Initiate) on Jan 19, 2009 at 11:39 UTC
    However, I need to maintain the distinction of scalar and array for different inputs. So, the first code really suites me! :)
    Thanks again!
      You can also distinguish that by looking at the number of elements of the array.


      holli, /regexed monk/