Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find out if the value of a variable in Perl is a scalar or an array?

Tags:

perl

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]?

like image 577
Daniel C. Sobral Avatar asked Nov 08 '10 20:11

Daniel C. Sobral


2 Answers

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

  • Documentation for the ref function: http://perldoc.perl.org/functions/ref.html
like image 139
zigdon Avatar answered Oct 14 '22 09:10

zigdon


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";
like image 35
Chas. Owens Avatar answered Oct 14 '22 08:10

Chas. Owens