develooper Front page | perl.beginners | Postings from September 2009

Checking subroutine inputs

Thread Next
From:
Philip Potter
Date:
September 6, 2009 03:15
Subject:
Checking subroutine inputs
Message ID:
91dd35300909060315o5e9c8fd3yaff2f04d4f9f87f3@mail.gmail.com
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.

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?

Philip


-- 
"I have always wished for my computer to be as easy to use as my
telephone; my wish has come true because I can no longer figure out
how to use my telephone."
  --Bjarne Stroustrup

Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About