How do I pass a hash to subroutine?

nebulus picture nebulus · Feb 4, 2011 · Viewed 42.4k times · Source

Need help figuring out how to do this. My code:

my %hash;
$hash{'1'}= {'Make' => 'Toyota','Color' => 'Red',};
$hash{'2'}= {'Make' => 'Ford','Color' => 'Blue',};
$hash{'3'}= {'Make' => 'Honda','Color' => 'Yellow',};


&printInfo(%hash);

sub printInfo{
   my (%hash) = %_;
   foreach my $key (keys %_{       
    my $a = $_{$key}{'Make'};   
    my $b = $_{$key}{'Color'};   
    print "$a $b\n";
    }
}

Answer

ghandi picture ghandi · Feb 4, 2011

The easy way, which may lead to problems when the code evolves, is simply by assigning the default array @_ (which contains all key-value-pairs as an even list) to the %hash which then rebuilds accordingliy. So your code would look like this:

sub printInfo {
   my %hash = @_;
   ...
}

The better way would be to pass the hash as reference to the subroutine. This way you could still pass more parameters to your subroutine.

printInfo(\%hash);
sub PrintInfo {
   my %hash = %{$_[0]};
   ...
}

An introduction to using references in Perl can be found in the perlreftut