How do I pass a function, a
, to function, b
, and have b
call a
in Perl?
The JavaScript call() Method The call() method is a predefined JavaScript method. It can be used to invoke (call) a method with an owner object as an argument (parameter). With call() , an object can use a method belonging to another object.
Just as passing objects to functions as arguments is an efficient way of moving information to where it's needed, so is using objects as return values. Functions can either manipulate objects that you pass to them and then return them, or they can return brand-new objects that they create in the function body.
To pass an object as an argument we write the object name as the argument while calling the function the same way we do it for other variables. Syntax: function_name(object_name); Example: In this Example there is a class which has an integer variable 'a' and a function 'add' which takes an object as argument.
You can pass an object as a parameter but not define it in the function definition.
Here's a complete, working script that demonstrates what you're asking.
sub a { print "Hello World!\n"; } sub b { my $func = $_[0]; $func->(); } b(\&a);
Here's an explanation: you take a reference to function a
by saying \&a
. At that point you have a function reference; while normally a function would be called by saying func()
you call a function reference by saying $func->()
The ->
syntax deal with other references as well. For example, here's an example of dealing with array and hash references:
sub f { my ($aref, $href) = @_; print "Here's an array reference: $aref->[0]\n"; # prints 5 print "Here's a hash ref: $href->{hello}\n"; # prints "world" } my @a = (5, 6, 7); my %h = (hello=>"world", goodbye=>"girl"); f(\@a, \%h);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With