How do closures in Perl work?

后端 未结 3 1378
花落未央
花落未央 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:38

    Every time you call the subroutine 'make_saying', it:

    1. creates a DIFFERENT closure

    2. assigns the received parameter to the scalar '$salute'

    3. defines (creates but not execute) an inner anonymous subroutine: That is the reason why at that moment nothing is assigned to the scalar $target nor is the statement print "$salute, $target!\n"; executed .

    4. finally the subroutine 'make_saying' returns a reference to the inner anonymous subroutine, that reference becomes the only way to call the (specific) anonymous subroutine.

    Ever time you call each anonymous subroutine, it:

    1. assign the received parameter to the scalar $target

    2. sees also the scalar $salute that will have the value assigned at the moment in which was created the anonymous subroutine (when was called its parent subroutine make_saying

    3. finally executes the statement print "$salute, $target!\n";

提交回复
热议问题