http://qs321.pair.com?node_id=765168

binf-jw has asked for the wisdom of the Perl Monks concerning the following question:

Dear monks,

I'm writing a method which removes the first argument of @_ if it is the blessed reference to the package or the class name / package, thus allowing several call syntaxes to be used for static methods (Not requiring any instance variables). I've had a quick super search but couldn't find anything.

Method example: ( Classic pow example ):
package Object; { # pow does not require an object data sub pow { my $val = shift; my $pow = shift; return $val ** $pow; } } 1;

I can quite happily call this method like so:
use Object Object::pow( 2, 2 );
or exported ( With some code added to the module):
use Object 'pow'; pow( 2,2 );


I thought it would be nice to call such method as any of the following:
Object->pow(2,2); Object::pow(2,2); my $obj = Object->new(); $obj->pow(2,2); pow(2,2); # Exported or internal method call

To accomplish this I wrote a method which filters the arguments:
sub rmvObjRef { my $package_name = shift; my $param1 = ref( $_[ 0 ] ) || $_[ 0 ]; # If param1 holds the name of the class / package # remove it from the arguments. if ( $param1 eq $package_name ) { shift @_; } return @_; }
or the one line equivalent to use inline:
shift if ref $_[0] eq __PACKAGE || $_[0] eq __PACKAGE__;
Which is called as follows.
@_ = rmvObjRef( __PACKAGE__, @_ );
The only draw back to my approach I can see is if the arguments contain the object reference which the method has been declared in at $_[0]:
package NumObject; sub addObjects { @_ = rmvObjRef( __PACKAGE__, @_ ); # Just an example, Obviously an overloaded '+' # op could achieve this. return NumObject + NumObject; }
Calling this as:
my $num1 = NumObject->new(); my $num2 = NumObject->new(); NumObject::addObjects( $num1, $num2 );
would remove $num1 from @_
Is there any way to just check just the left argument of the infix dereference operator "->"?

Many Thanks,
John,