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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With