On Mon, Sep 21, 2009 at 11:58:30AM +0100, Alex Francis wrote:

> The other day, I confidently told a colleague that it was better to
> use Scalar::Util::reftype to check e.g. whether a scalar holds a
> reference to an array:
>     if ( reftype( $param ) && reftype( $param ) eq 'ARRAY' ) {
> 
> instead of using CORE::ref
>     if ( ref( $param ) eq 'ARRAY' ) {
> 
> I mentioned this was what PBP recommended. He asked me what the
> reasoning was, which was the point where I thought "err....."
> 
> All I can come up with is that reftype is easier to read because it
> returns what it sounds like it returns, whatever you give it, whereas
> ref returns the class of an object, or if it's not an object then the
> type of a reference.

That's a good enough reason for me.  It's syntactic sugar, as there are
all kinds of other ways of doing this, but it's *good* sugar.

Other ways of doing it, all of which require some care ...

  $foo->isa('ARRAY')            # if $foo is known to be an object
  UNIVERSAL::isa($foo, 'ARRAY') # if it might not be. This will ignore
                                # any isa() defined in an object or any
                                # of its superclasses
  eval { @{$foo}; 1 } && !$@    # but beware operator overloading

For the last of those, you can get around the operator overloading
problem using Acme::Damn to get an unblessed version of the
reference.  But really, why would you bother when you can just use
reftype ;-)

-- 
David Cantrell | top google result for "topless karaoke murders"

You can't spell "slaughter" without "laughter"
_______________________________________________
BristolBathPM mailing list
[email protected]
http://mailman.bristolbath.org/mailman/listinfo/bristolbathpm

Reply via email to