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 ):
I can quite happily call this method like so:
I thought it would be nice to call such method as any of the following:
To accomplish this I wrote a method which filters the arguments:
Is there any way to just check just the left argument of the infix dereference operator "->"?
Many Thanks,
John,
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:
or exported ( With some code added to the module):use Object Object::pow( 2, 2 );
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:
or the one line equivalent to use inline: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 @_; }
Which is called as follows.shift if ref $_[0] eq __PACKAGE || $_[0] eq __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]:@_ = rmvObjRef( __PACKAGE__, @_ );
Calling this as:package NumObject; sub addObjects { @_ = rmvObjRef( __PACKAGE__, @_ ); # Just an example, Obviously an overloaded '+' # op could achieve this. return NumObject + NumObject; }
would remove $num1 from @_my $num1 = NumObject->new(); my $num2 = NumObject->new(); NumObject::addObjects( $num1, $num2 );
Is there any way to just check just the left argument of the infix dereference operator "->"?
Many Thanks,
John,
|
---|
Back to
Seekers of Perl Wisdom