On Sun, Sep 6, 2009 at 06:15, Philip Potter<philip.g.pot...@gmail.com> wrote: > Dear all, > > I have a subroutine which takes an indirect filehandle and a Graph > object as its two inputs. I'd like to check that I've been given the > correct types in the subroutine, so that if I get it wrong I get a > sensible error message. Here's what I've tried so far: > > sub writefsg { > my ($filename,$graph) = @_; > if (!ref($graph) || !$graph->isa('Graph')) { croak > q{Pgp::Graph::FSG::writefsg didn't get a Graph object}; } > # do work > return; > } > > This test works if there is no second argument or if it is an integer, > string, or object reference; but if I pass in an array reference I get > "'Can't call method "isa" on unblessed reference". Technically this > does the right thing -- dies -- but reports the wrong error message, > so is somewhat suboptimal. snip
It sounds like you want the blessed function from [Scalar::Util][1]: croak "Pgp::Graph::FSG::writefsg didn't get a Graph object" unless blessed $graph and $graph->isa('Graph'); snip > What is the idiomatic perl for checking that an argument is what it > should be? Does it vary depending on whether you expect a number, a > string, an array reference, a hash reference, a filehandle, or an > object reference? Where can I find a discussion of passing subroutine > arguments, including discussion of checking number and type? snip If you are using an OO style then you should really look into [Moose][2]. It is Perl 6's object module backported to Perl 5. I would also suggest using [MooseX::Declare][3] which changes the way Perl 5 parses code to allow a simple declarative style of creating classes: #warning untested code to give you an idea of what it looks like class Point::2D { has x => (is => "rw", isa => "Int", required => 1); has y => (is => "rw", isa => "Int", required => 1); method _find_square (Point::2D $other) { return ($self->x - $other->x) ** 2 + ($self->y - $other->y) ** 2; } method find_distance (Point::2D $other) { return sqrt $self->_find_square($other) } } class Point::3D extends Point::2D { has z => (is => "rw", isa => "Int", required => 1); #wrap Point::2D's _find_square and add our functionality around _find_square (Point::3D $other) { return $self->$orig + ($self->z - $other->z) ** 2; } } 1. http://perldoc.perl.org/Scalar/Util.html#blessed-EXPR 2. http://search.cpan.org/dist/Moose/lib/Moose/Manual.pod 3. http://search.cpan.org/dist/MooseX-Declare/lib/MooseX/Declare.pm -- Chas. Owens wonkden.net The most important skill a programmer can have is the ability to read. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/