Exploring the uses of anonymous subs

Viewed 2955

I've always been somewhat confused about the purpose and usage of anonymous subs in perl. I understand the concept, but looking for examples and explanations on the value of this practice.

To be clear:

sub foo { ... }   # <--- named sub
sub { ... }       # <--- anonymous sub

For example:

$ perl -e 'print sub { 1 }'
CODE(0xa4ab6c)

Tells me that sub returns a scalar value. So, I can do:

$ perl -e '$a = sub { 1 }; print $a'

For the same output as above. This of course holds true for all scalar values, so you can load arrays or hashes with anonymous subs.

The question is, how do I use these subs? Why would I want to use them?

And for a gold star, is there any problem which can only be resolved with an anonymous sub?

8 Answers
Related