jeanluca has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I really need to find a way to find out what type/instance of a variable is: is $a a hash, int, float. array or maybe an instance of myNewModule! How do you test for this, for example, in an if statement ?

Cheers
Luca

Replies are listed 'Best First'.
Re: The instance/type of a variable
by dragonchild (Archbishop) on Oct 19, 2005 at 13:22 UTC
    ref() is a good start. Scalar::Util provides a number of other options, such as looks_like_number() (which tells you if something is probably a number), blessed() (which returns the class it's blessed into, if any). As for int vs. float, that's easy - int($a) == $a means it's an int.

    The important point here is that when you program in Perl, you shouldn't have to worry about int vs. float. Personally, I tend to not worry about anything except reference, object, and non-reference.


    My criteria for good software:
    1. Does it work?
    2. Can someone else come in, make a change, and be reasonably certain no bugs were introduced?
      All this helps a lot!!!!
      Thanks
      Luca
Re: The instance/type of a variable
by Zaxo (Archbishop) on Oct 19, 2005 at 13:03 UTC

    ref returns the builtin type or class name of a variable containing a reference.

    After Compline,
    Zaxo

Re: The instance/type of a variable
by philcrow (Priest) on Oct 19, 2005 at 13:05 UTC
    You can use ref for some of that:
    if ( ref( $your_var ) =~ /HASH/ ) { ... }
    or in more draconian fashion
    if ( ref( $your_var ) eq 'HASH' ) {...}
    It won't tell you whether a scalar is a string or a number.

    Phil

Re: The instance/type of a variable
by BerntB (Deacon) on Oct 19, 2005 at 13:03 UTC
    Check ref(), it does what you want -- except differ between SCALAR types.

    To differ between scalars, I do kludgy stuff (like add 0 and see if the result is not-zero and =~ /^\s*0\s*$/.) (-: Someone else will certainly answer better. :-)

Re: The instance/type of a variable
by jeanluca (Deacon) on Feb 11, 2006 at 16:14 UTC
    The date is year-julian. One last question: If I would like to allow the following formats:
    2005-111 2005111 2005
    Somehow this doesn't work:
    $a = $some_date ; if ( $a =~ /\d{4}-?\d{3}?/ ) { .... }
    Any suggestions why this doesn't work ?
    Thanks a lot
    Luca