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 −

Example

 Live Demo

#!/usr/bin/perl # 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. &$cref(%hash);

Output

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

Item : name Item : Tom Item : age Item : 19
Updated on: 2019-11-29T09:59:08+05:30

220 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements