How do closures in Perl work?

后端 未结 3 1393
花落未央
花落未央 2021-02-18 20:19

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  {         


        
3条回答
  •  青春惊慌失措
    2021-02-18 20:56

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

提交回复
热议问题