Alex Rivera | Logout

Why would I use Perl anonymous subroutines instead of a named one?

Asked 2009-05-07T13:15:32.770
20

I'm just curious why one would choose to use an anonymous subroutine, versus a named one, in Perl. Thanks.

Edit
Report

2 Answers

8

I talk about anonymous subroutines and why you would use them in Mastering Perl. In short, you start thinking about behavior as just another form of data just like you think about strings or numbers. When you are comfortable with that idea, you can do some pretty amazing things because you can push off a lot of decisions to very late in the program and you don't have to contort your code design to deal ahead of time with every situation that might show up.

You can write code knowing that you are going to run a subroutine, only you don't know which one yet. You trust the previous steps to work that out for you. Once you can do that, you're on another level of programming that feels like you're writing code to create your program for you. Some programming problems become much easier to solve this way.

And, like every other feature, you can take this too far or use it inappropriately.

answered 2009-05-09T19:56:52.513
1

First: sub thing is a sub. my $thing=sub... is a sub reference stored in a variable.

Second: There's a subtle usage difference:

use strict;
use warnings;

sub xx {
  my $zz=1;

   sub yy {
      print $zz;
   }
}


perl tmp.pl
Variable "$zz" will not stay shared at tmp.pl line 8.

Change [sub yy...] to [my $yy = sub {...] or [local *yy = sub{...] and the complaint goes away.

Also, to be honest, references-to-subs are just easier to deal with, much the same as @x=(1,2,3) versus $x=[1, 2, 3].

answered 2009-05-07T13:29:32.923

Your Answer