Passing Hashes to Subroutines in Perl

PERLServer Side ProgrammingProgramming Scripts

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
raja
Published on 29-Nov-2019 06:57:13
Advertisements