Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a Function Object and Calling it

Tags:

reference

perl

How do I pass a function, a, to function, b, and have b call a in Perl?

like image 579
Kys Avatar asked Aug 05 '09 17:08

Kys


People also ask

How do you call a function object?

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.

Can you pass an object into a function?

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.

How is an object passed through a function?

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.

Can a function pass an object as a parameter?

You can pass an object as a parameter but not define it in the function definition.


1 Answers

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); 
like image 197
Eli Courtwright Avatar answered Sep 20 '22 18:09

Eli Courtwright