Alex Rivera | Logout

How does the closure mechanism work in Perl?

Asked 2013-06-11T08:18:27.350
24

Newbie in Perl again here, trying to understand closure in Perl.

So here's an example of code which I don't understand:

sub make_saying  {
    my $salute = shift;
    my $newfunc = sub {
        my $target = shift;
        print "$salute, $target!\n";
    };
    return $newfunc;            # Return a closure
}
$f = make_saying("Howdy");      # Create a closure
$g = make_saying("Greetings");  # Create another closure
# Time passes...
$f->("world");
$g->("earthlings");

So my questions are:

  1. If a variable is assigned to a function, is it automatically a reference to that function?
  2. In that above code, can I write $f = \make_saying("Howdy") instead? And when can I use the & because I tried using that in passing the parameters (&$f("world")) but it doesn't work.
  3. and lastly, in that code above how did the strings world and earthlings get appended to the strings Howdy and Greetings.

Note: I understand that $f is somewhat bound to the function with the parameter "Howdy" so that's my understanding how "world" got appended. What I don't understand is the 2nd function inside. How that one operates its magic. Sorry I really don't know how to ask this one.

Edit
Report

1 Answer

4

If a variable is asigned to a function, is it automatically a reference to that function?

No. In example the function make_saying return reference another function. Such closures do not have name and can catch a variable from outside its scope (variable $salute in your example).

In that above code, can i write $f = \make_saying("Howdy") instead? And when can i use the & cause i tried using that in passing the parameters (&$f("world")) but it doesnt work.

No. $f = \make_saying("Howdy") is not what you think (read amon post for details). You can write $f = \&make_saying; which means "put into $f reference to function make_saying". You can use it later like this:

my $f = \&make_saying;
my $other_f = $f->("Howdy");
$other_f->("world");

and lastly, In that code above how in he** did the words world and earthlings got appended to the words howdy and greetings.

make_saying creating my variable which goes into lamda (my $newfunc = sub); that lambda is returned from make_saying. It holds the given word "Howdy" through "closing" (? sorry dont know which word in english).

answered 2013-06-11T08:29:55.743

Your Answer