References to Functions in Perl

While using Perl script, this might happen if you need to create a signal handler so you can produce a reference to a function by preceding that function name with \& and to dereference that reference you simply need to prefix reference variable using ampersand &. Following is an example −


 Live Demo

# Function definition
sub PrintHash {
   my (%hash) = @_;
   foreach $item (%hash) {
      print "Item : $item\n";
%hash = ('name' => 'Tom', 'age' => 19);
# Create a reference to above function.
$cref = \&PrintHash;
# Function call using reference.


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

Item : name
Item : Tom
Item : age
Item : 19