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:
- If a variable is assigned to a function, is it automatically a reference to that function?
- 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. - and lastly, in that code above how did the strings
worldandearthlingsget appended to the stringsHowdyandGreetings.
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.