Does anyone know how to understand this type of blocks of Perl code?

I am confused by Perl Named Blocks (I thought they were ...). The following is an example:

#!/usr/bin/perl sub Run(&){ my ($decl) = @_; $decl->(); } sub cmd(&){ my($decl) = @_; my(@params) = $decl->(); print "@params\n"; } sub expect(&){ my ($decl) = @_; my(@params) = $decl->(); print "@params\n"; } Run { cmd { "echo hello world " }; expect { exit_code => 0, capture => 2}; }; 

Pay attention to the last lines. It looks like this: "Run", "cmd", "expect" are named blocks, but not functions. Does anyone know what it is? Any available link introduce them? I can not find links to such a grammar.

+6
source share
3 answers

Let me decipher this definition for Run :

 sub Run(&){ my ($decl) = @_; $decl->(); } 

This means a routine called Run , which takes a parameter of type CODE (therefore uses (&) ). Inside it, $decl assigned this passed code, and this code is called $decl->(); .

Now, the last lines in your example:

 Run { cmd { "echo hello world " }; expect { exit_code => 0, capture => 2}; }; 

equivalent to:

 Run(sub { cmd { "echo hello world " }; expect { exit_code => 0, capture => 2}; }); 

In other words, it calls Run with an anonymous procedure code, which is in braces.

+9
source

Run , cmd and expect are prototype specific functions, and they work as built-in functions (no need to write sub{..} , as this is implied due to the (&) signature for these functions).

If these functions were defined without prototypes,

 sub Run { .. } sub cmd { .. } sub expect { .. } 

then explicit sub{} arguments will not be optional, but necessary,

 Run(sub{ cmd(sub{ "echo hello world " }); expect(sub{ exit_code => 0, capture => 2}); }); 
+5
source

They are routines that take a block as an argument. See: http://perldoc.perl.org/perlsub.html#Prototypes . (&) in their definitions means that their first argument is a block of code.

+4
source

Source: https://habr.com/ru/post/971645/


All Articles