How do I know if a variable's value in Perl is a scalar or an array?

Let's say I have this:

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

How can I find out later that what was saved was a scalar, for example, in "abc" , or an array, as in [1, 2, 3] ?

+7
perl
source share
2 answers

First of all, your array reference example is incorrect - your $hash{"b"} will have a scalar value : the last element of the list that you specified ('c' in this case).

However, if you really want to see if you have a scalar or link, use the ref function:

 my %hash; $hash{"a"} = "abc"; $hash{"b"} = [qw/abc/]; if (ref $hash{"b"} eq 'ARRAY') { print "it an array reference!"; } 

Docs

+13
source share

First, $hash{"b"} = qw/abc/; will store 'c' in $hash{"b"} , not an array, maybe you mean $hash{"b"} = [ qw/abc/ ]; , which will store the array reference in $hash{"b"} . This is a key bit of information. Everything except the scalar should be stored as a link when assigned to the scalar. There is a function called ref that will tell you the link information, but it will give you the class name of the object if the link was blessed. Fortunately, there is another function called reftype that always returns the structure type 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"; 
+8
source share

All Articles