References to Functions in Perl

PERLServer Side ProgrammingProgramming Scripts

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
";    } } %hash = ('name' => 'Tom', 'age' => 19); # Create a reference to above function. $cref = \&PrintHash; # Function call using reference. &$cref(%hash);


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

Item : name
Item : Tom
Item : age
Item : 19
Updated on 29-Nov-2019 09:59:08