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,
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.