Recently, I've noticed a few places where anonymous subroutines have been declared for no apparent reason:
I would write the same subroutine as such:my $function = sub { # ...do stuff... }; # Call the sub $function->('param');
The above two code snippets appear to do exactly the same thing. But is there a subtle difference lurking there that I have overlooked? Is there a reason to write the first form instead of the second?sub function { # ...do stuff... } # Call the sub function('param);
I don't think I have ever written a stand-alone anonymous subroutine like this. The only place I generally use anonymous subs is as a 'value' in a hash. Typically, to pass to Template to keep logic separated from display like this:
my $vars = { 'date' => $date, 'format' => sub { return ucfirst lc $_[0]; }, }; $template->process('example.tt', $vars);
In reply to Anonymous subroutines by Bod
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |