Alex Rivera | Logout

Can Perl detect arrays?

Asked 2011-03-07T23:53:28.487
29

I have this script

#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

my %x1 = ();
$x1{"a"} = "e";

my %x2 = ();
$x2{"a"} = ["b","c"];

p(\%x1);
p(\%x2);

sub p {
    my $x = shift @_;
    print $x->{a};
    print "\n";
}

which outputs

e
ARRAY(0x2603fa0)

The problem is I don't know when the input is an array or a scalar, and when it is an array I would like to print those values as well.

Can p be modified to do this?

Edit
Report

1 Answer

57

Yes, perl can detect what type a variable is. Use the ref() function. For example:

if (ref($var) eq 'ARRAY') {
   # Do stuff
}

See more in this perlmonks discussion.

answered 2011-03-07T23:59:10.733

Your Answer