Passing Hashes to Subroutines in Perl


When you supply a hash to a Perl subroutine or operator that accepts a list, then the hash is automatically translated into a list of key/value pairs. For example −

Example

 Live Demo

#!/usr/bin/perl
# Function definition
sub PrintHash {
   my (%hash) = @_;
   foreach my $key ( keys %hash ) {
      my $value = $hash{$key};
      print "$key : $value\n";
   }
}
%hash = ('name' => 'Tom', 'age' => 19);
# Function call with hash parameter
PrintHash(%hash);

Output

When the above program is executed, it produces the following result −

name : Tom
age : 19

Updated on: 29-Nov-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements