Re: Usage of ref for testing if a passed in reference is a HASH, etc

[prev] [thread] [next] [Date index for 2004/11/17]

From: Michael Henson
Subject: Re: Usage of ref for testing if a passed in reference is a HASH, etc
Date: 15:43 on 17 Nov 2004
On Fri, 2004-11-12 at 23:16 +0200, Yuval Kogman wrote:
> On Fri, Nov 12, 2004 at 13:51:23 -0500, Michael Henson wrote:
> > Many places in Class::DBI use ref to determine if a given value is a
> > reference to an array or a hash. Wouldn't it be better to use
> > UNIVERSAL::isa, esp if the only purpose is to make sure that accessing a
> > key makes sense?
> 
> What's the difference?
> 
> Personally I prefer Scalar::Util's reftype, just because it's easier
> to figure out what the programmer was testing for without actually
> reading into the line of code.
> 

Yeah, reftype if probably clearer.

>
> If you mean testing whether a /blessed/ reference is of the correct
> class, not that a reference is to the correct data type, then
> nonononononono!!! UNIVERSAL::isa is crummy. Called that way, that
> is. ->isa is a method. Scalar::Util::blessed($thing) &&
> $thing->isa('class') is the way to go.
> 

I was referring to just testing to ensure it is the correct data type.

Right now ->create work likes this:
sub create {
        my $class = shift;
        return $class->_croak("create needs a hashref") unless ref $_[0]
eq 'HASH';
        my $info = { %{ +shift } };    # make sure we take a copy


Which is all well and good, but it doesn't allow you to do things like
this:

my $foo = bless( { name => 'Testing', prop1 => 2 },
'SomeClassOrAnother' );

my $obj = OurClassDBIPkg->create( $foo );

I am not sure if this would even be a desired feature, as opposed to
just doing some proprocessing, etc, but it seems sensible enough and
would make things much easier when working with a toolkit like
SOAP::Lite which will bless input hash-refs into a pkg depending on the
xml-schema type.

        -- 
        Michael Henson <michael@xxxxxx.xxx>

Re: Usage of ref for testing if a passed in reference is a HASH, etc
Michael Henson 15:43 on 17 Nov 2004

Generated at 17:31 on 15 Feb 2005 by mariachi v0.52