in reply to Blessing interior hashes

What I want to test for is like Is the underlying implementation of this blessed thing a hashref?

reftype($ref) eq 'HASH' answers that question.
reftype can be found in core module Scalar::Util.

UNIVERSAL::isa($ref, 'HASH') also answers that question.
isa is always present. It's documented in core module UNIVERSAL.

...but is it the right question? Shouldn't you be asking "Can this ref be used as a hashref?"

eval { %$ref || 1 } will answer that question.

if (eval { %$ref || 1 }) { # Hash ... } elsif (eval { @$ref || 1 }) { # Array ... } else { ... }

Update: Added isa.

Replies are listed 'Best First'.
Re^2: Blessing interior hashes (pseudo-hashes)
by lodin (Hermit) on Oct 03, 2007 at 19:38 UTC

    Beware that eval { %$ref } may emit a warning.

    my $ref = [{}]; eval { %$ref || 1 }; __END__ Pseudo-hashes are deprecated at ...

    lodin

      Good catch. In the presented if/elsif scenario, you can avoid this by checking for arrays first.
Re^2: Blessing interior hashes
by throop (Chaplain) on Oct 03, 2007 at 17:41 UTC
    Thanks, ikegami. I'll use that.

    I was initially puzzled—what is going inside those eval's? Let me see if I've puzzled it out right:

    • If $ref is a reference to a hash, then %$ref will eval to something legal.
      • It's possibly an empty hash.
      • The '|| 1' assures a true value.
    • If $ref is not a reference to a hash or something that can be used as a hash, then
      • an error occurs.
      • eval returns undef.
      • $@ would contain an error message if we checked it (but we don't because the undef told us all we need to know.)
    Right?

    throop

      Yup, excellent!

      Two little additions:
      || 1 assures a true value when %$ref is an empty hash.
      || 1 avoids the "void context" warning ; 1 would issue.

      One little correction:
      On error, eval returns false (dualvar 0, ""), not undef.

        On error, eval returns false (dualvar 0, ""), not undef.

        From perlfunc:

        If there is a syntax error or runtime error, or a die statement is executed, an undefined value is returned by eval

        lodin