cajwine
cajwine

Reputation: 3160

Arguments of anonymous subroutines in the BEGIN block

I one source code i saw the next construction:

our %hash;
BEGIN {
    %hash = (
         KEY1 =>
          sub { return $_[0]->somefunc( 1, $_[2]->attr1, $_[2]->attr2 ); },
         KEY2 =>
          sub { return $_[0]->somefunc( 0, $_[2]->attr1, $_[2]->attr2 ); },
         ...
    );
}

What are those $_[0] (they are the first arg of anonymous sub) - but here are in the BEGIN block... so, what is its value at "compilation" phase?

The $hash{KEY1} get a subroutine reference, but to what subroutine?

EDIT

Now (i hope) understand. Just dumped the content of the %hash with Data::Dumper::Concise and got the next:

  ...
  KEY1 => sub {
      package MyPkg;
      use warnings;
      use strict;
      return $_[0]->somefunc(1, $_[2]->attr1, $_[2]->attr2);
  },
  KEY2 => sub {
      package MyPkg;
      use warnings;
      use strict;
      return $_[0]->somefunc(0, $_[2]->attr1, $_[2]->attr2);
  },
  ...

So, the construction returns a reference to anonymous sub, what when will be executed returns the result of execution of $_[0]->somefunc with the supplied args.

Upvotes: 1

Views: 97

Answers (1)

ysth
ysth

Reputation: 98398

sub {} creates an anonymous subroutine and returns a reference to it (just as [] and {} do with arrays and hashes).

The $_[0], etc., are the arguments to that sub.

So if you call $hash{KEY1}->('foo','bar','baz'), $_[0] will be 'foo'.

The fact that the anonymous sub was generated at compile time isn't relevant.

Upvotes: 3

Related Questions