Programming

(Perl) Passing a Function Object and Calling it

steloflute 2013. 10. 1. 13:00

http://stackoverflow.com/questions/1234640/passing-a-function-object-and-calling-it



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);



'Programming' 카테고리의 다른 글

Simplified Common Lisp reference  (0) 2013.10.24
regular expression  (0) 2013.10.04
(Perl) match the shortest possible string  (0) 2013.09.23
perlintro  (0) 2013.09.16
(JavaScript) refresh or close???  (0) 2013.09.12