Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the syntax used for sub foo : method { shift->bar(@_) }?

Tags:

perl

sub foo : method { shift->bar(@_) }

What does : method mean here?

I've never used it this way ...

like image 946
asker Avatar asked Aug 24 '11 01:08

asker


1 Answers

: method is function attribute description. A subroutine so marked will not trigger the "Ambiguous call resolved as CORE::%s" warning.

From ysth's comment:

The warning happens when the sub has the same name as a builtin and it is called without & and not as a method call; perl uses the builtin instead but gives a warning. The :method quiets the warning because it clearly indicates the sub was never intended to be called as a non-method anyway.

Update

This code just calls method bar when foo is called:

sub foo : method {  ## Mark function as method
    shift->bar(@_)  ## Pass all parameters to bar method of same object
}

More details:

  • : method - Indicates that the referenced subroutine is a method. A subroutine so marked will not trigger the "Ambiguous call resolved as CORE::%s" warning.
  • shift - gets first parameter from @_, which will be $self
  • ->bar(@_) - call same class method bar with all other parameters

You can read this as:

sub foo : method {
    my ($self) = shift @_; 
    return $self->bar(@_);
}
like image 147
Ivan Nevostruev Avatar answered Nov 17 '22 20:11

Ivan Nevostruev