9

Say I have this:

my %hash;

$hash{"a"} = "abc";
$hash{"b"} = [1, 2, 3];

How can I, later on, find out if what was stored was a scalar, like in "abc", or an array, like in [1, 2, 3]?

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
  • possible duplicate of [How do I tell what type of value is in a Perl variable?](http://stackoverflow.com/questions/1731333/how-do-i-tell-what-type-of-value-is-in-a-perl-variable) – Ether Nov 08 '10 at 20:21

2 Answers2

17

First of all, your example of an array reference is wrong - your $hash{"b"} will end up with a scalar value: the last element of the list you provided ('c' in this case).

That said, if you actually do want to see if you have a scalar or a reference, use the ref function:

my %hash;

$hash{"a"} = "abc";
$hash{"b"} = [qw/a b c/];

if (ref $hash{"b"} eq 'ARRAY') {
  print "it's an array reference!";
}

Docs

zigdon
  • 14,573
  • 6
  • 35
  • 54
  • 2
    Note that, in the OP's code, `$hash{b}` ends up being `'c'` rather than `['a', 'b', 'c']` as he wants (or 3 as I initially expected it to). – Chris Lutz Nov 08 '10 at 20:20
  • Silly mistake -- bad copy&paste from somewhere else just to get some simple code for the question. – Daniel C. Sobral Nov 08 '10 at 20:37
8

First off, $hash{"b"} = qw/a b c/; will store 'c' in $hash{"b"}, not an array, you may have meant $hash{"b"} = [ qw/a b c/ ]; which will store a reference to an array in to $hash{"b"}. This is the key bit of information. Anything other than a scalar must be stored as a reference when assigned to a scalar. There is a function named ref that will tell you information about a reference, but it will hand you the name of the object's class if the reference has been blessed. Happily there is another function named reftype that always returns they type of the structure in Scalar::Util.

#!/usr/bin/perl

use strict;
use warnings;

use Scalar::Util qw/reftype/;

my $rs  = \4;
my $ra  = [1 .. 5];
my $rh  = { a => 1 };
my $obj = bless {}, "UNIVERSAL";

print "ref: ", ref($rs), " reftype: ", reftype($rs), "\n",
    "ref: ", ref($ra), " reftype: ", reftype($ra), "\n",
    "ref: ", ref($rh), " reftype: ", reftype($rh), "\n",
    "ref: ", ref($obj), " reftype: ", reftype($obj), "\n";
Chas. Owens
  • 64,182
  • 22
  • 135
  • 226
  • What strikes me as being odd is [why `ref $fileHandle` doesn't return 'IO'](http://stackoverflow.com/questions/2955428/when-does-refvariable-return-io) – Zaid Nov 09 '10 at 04:46
  • @Zaid They could have done that, but then all of the legacy code that expects a typeglob would have broken with the new lexical filehandles. Perl 5 has always strived to not break existing code; you can understand many of the odd choices when you keep that in mind. – Chas. Owens Nov 09 '10 at 14:10