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]
?
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
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With