📜 ⬆️ ⬇️

On demand functions

Did you know that in PERL 'e you can create functions on demand, on the fly?
What is it and why it may be needed?

Let's say you have a html_tag function:

sub html_tag {
my $tag = shift;
my $msg = shift;
return sprintf( '<%s>%s</%s>' , $tag, $msg, $tag);
}


')
and you want to do a lot of functions with the names of the corresponding html tags. You can, of course, manually write all the function definitions:

sub h1 { return html_tag( 'h1' ,@_); }
sub h2 { return html_tag( 'h2' ,@_); }
sub h3 { return html_tag( 'h3' ,@_); }
...



but somehow this is wrong, too many letters. It turns out that there is a more beautiful way to solve this problem.



my @tags = qw(h1 h2 h3 p div span ul ol li em strong );
for my $tag (@tags) {
no strict 'refs' ;
*$tag = sub { return html_tag($tag,@_); };
}



We describe all the necessary function names and add references to them in the global symbol table of the package. Actually, all the magic is contained in the string

* $ tag = sub { return html_tag ($ tag, @ _); };

sub {} returns a reference to an anonymous function (within which the html_tag is called with the same tag as the first argument).

and the assignment * $ tag = adds the function name (contained in the $ tag variable) to the global symbol table of the package ( typeglob ).

Now our functions can be used like this:

print
ul(
li( ' ' ).
li( ' ' ).
li( ' ' )
);



And most importantly, to add another function, all you need is to edit the line with the names of the functions!

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


All Articles