Seek Perl idiom to check that $self is a class or object -
in perl, got bitten looked bug below:
package foo; sub method { $self = shift; @args = @_; ... } where called subroutine, not method:
foo::method( "arg1", "arg2" ); rather calling method - in case, "class method":
foo->method( "arg1", "arg2" ); calling foo::method("arg1","arg2") resulted in "arg1" getting dropped.
similar considerations can arise "object method":
my $object = foo->new(); $obj->method( "arg1", "arg2" ); q: there friendly, concise, perl idiom checking first argument, conventionally called $self, in fact object in class (package), and/or class/package name?
the best have come is:
package foo; sub method { $self = ($_[0]->isa(__package__) ? shift @_ : die "...error message..."; @args = @_; ... } which not more concise
package foo; sub method { $self = shift; die "...error message..." if $self->isa(__package__); @args = @_; ... } or
package foo; use carp::assert; sub method { $self = shift; assert($self->isa(__package__)); @args = @_; ... } ===
notes:
i know perl signatures, dislike using experimental features.
i know "use attributes", http://perldoc.perl.org/attributes.html, , :method. best way go? similar concerns "evolving" features.
i know moose - don't think moose enforces this. (did miss anything.)
the problem perl there many ways something.
i omitted "use strict; use warnings;" brevity.
the best answer not mix functions , methods in single package. "hybrid modules", they're known, problematic. might want make function should instead class method call.
there should little need qualify function call in day-to-day programming.
the concise way use moops new way use moose syntax-sugar.
use moops; class foo { method something() { print("something called\n"); } } foo->new->something(); foo::something(); # called # invocant $self required @ /users/schwern/tmp/test.plx line 10. moops marked unstable, that's interface, not signatures themselves. signatures have been around , usable in production long time, longer they've been built in. more worrying there hasn't been release in on year, author writes stuff. call.
otherwise, else, write function.
use carp; use scalar::util qw(blessed); sub check_invocant { $thing = shift; $caller = caller; if( !defined $thing ) { croak "the invocant not defined"; } elsif( !ref $thing ) { croak "the invocant not reference"; } elsif( !blessed $thing ) { croak "the invocant not object"; } elsif( !$thing->isa($caller) ) { croak "the invocant not subclass of $caller"; } return $thing; } since returns invocant , handles exception can used concisely.
package foo; sub method { $self = ::check_invocant(shift); ... }
Comments
Post a Comment