Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to use self invoking anonymous function in Perl?

Tags:

perl

It is a common practice to use self invoking anonymous functions to scope variables etc. in JavaScript:

;(function() {
  ...
})();

Is it a good practice to use such functions in Perl ?

(sub {
  ...
})->();

Or is it better for some reason to use main subroutine ?

sub main {
  ...
}

main();
like image 956
Igor Gilyazov Avatar asked Jan 27 '26 02:01

Igor Gilyazov


1 Answers

Perl has lexical scoping mechanisms JS lacks. You are better off simply enclosing code you want scoped somehow in a block, e.g.:

{
    my $localvar;
    . . .
}

In this case $localvar will be completely invisible outside of those braces; that is also the same mechanism one can use to localise builtin variables such as $/:

{
    local $/ = undef;
    #reading from a file handle now consumes the entire file
}
#But not out here

(Side note: never set $/ globally. It can break things in subtle and horrible ways if you forget to set it back when you're done, or if you call other code before restoring it.)

In perl, the best practise is to put things in subs when it makes sense; when it doesn't make sense or unnecessarily complicates the code, lexical blocks ensure scoping; if you do need anonymous subroutines (generally for callbacks or similar) then you can do my $subref = sub { . . . }; or even just stick the sub declaration directly into a function argument: do_something(callback => sub { . . . });

Note: see also ysth's answer for a resource-related advantage to self-invoking anonymous subs.

like image 200
Vector Gorgoth Avatar answered Jan 29 '26 16:01

Vector Gorgoth