Question

Why would I use Perl anonymous subroutines instead of a named one? inspired me to think about the merit of:

  • Storing anonymous subs in arrays, hashes and scalars.

It's a pretty cool concept, but is it practical in any way? Is there any reason why I'd have to use anonymous subs/sub references stored in some sort of data structure? Or perhaps a situation where it will be convenient?

I understand why anonymous subs are required in certain contexts such as dealing with shared variables (when an anonymous sub is declared inside another sub), but unless I'm missing something, I just don't see the point of using any sort of function reference. It seems like we should just call the functions outright and the code would look much nicer/more organized.

Please tell me I'm wrong. I'd love to have a good reason to use these things.

Thanks in advance.

Was it helpful?

Solution 2

Object-oriented methods are very much akin to anonymous subroutines. Polymorphism means that an object's methods can change without the calling code having to do lookups manually to see what routine to run. And that's VERY useful.

Also, think about perl's sort. Why set up a named routine just for a simple sort method? Ditto map and grep.

As well, iterators are very useful. Also, think about storing a routine that can be resolved later, rather than only being able to store a static value.

In the end, if you don't want to store anonymous routines (or even references to routines) that's your business. But having the option is way better than not having it.

OTHER TIPS

A dispatch table is useful for dynamically determining steps to take based on some value:

my %disp = (
   foo => sub { 'foo' },
   bar => sub { 'bar' },
);

my $cmd = get_cmd_somehow();
if (defined $disp{$cmd}) {
  $disp{$cmd}->(@args)
} else {
  die "I don't know how to handle $cmd"
}

(Method dispatch via ->can($method) is conceptually similar, but more flexible and the details are hidden.)

Anonymous functions and lexical closure has many other uses; perhaps look deeper into "higher-order functions." (Think about map()/grep(), for example.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top