Perl: Hashes as reference/function parameter
Following program illustrates how a hash can be passed as a function parameter and also can be referenced: The function is passed hashmap parameter:
%cityHash = (); $cityHash("delhi") = "india"; $cityHash("london") = "uk"; printCityHash(\%cityHash);
In the function, printCityHashwe access the hasmap as follows:
sub printCityHash{ my($hashRef) = @_; print "er"; foreach $city ( keys %$hashRef) { print STDERR "$city: $hashRef->{$city} \n"; }
Thus, the complete program that outputs the hashmap result is:
#!/usr/bin/perl %cityHash = (); $cityHash{"delhi"} = "india"; $cityHash{"london"} = "uk"; printCityHash(\%cityHash); sub printCityHash{ my($hashRef) = @_; print "er"; foreach $city ( keys %$hashRef) { print STDERR "$city: $hashRef->{$city} \n"; } }