Software Engineer

perl – check data type

· by jsnby · Read in about 1 min · (154 Words)
Computers

I was writing some code to parse an XML input file and noticed that XML::Simple was sometimes returning a data structure that had a single instance of a particular sub-element, and other times it would return an array of sub elements. For example, if I had:

<root>
    <sometag>foo</sometag>
</root>

I would get a root that points at a single scalar of sometag. But if I have this:

<root>
    <sometag>foo</sometag>
    <sometag>bar</sometag>
</root>

Then, I would get back a root that points at an array of sometags. So, to handle this, I needed to check to see if what I got back from the parser was a scalar variable or an array. I wasn’t quite sure how to do this, so I did a couple quick google searches. I found the UNIVERSAL::isa() method will do what I want. Here’s a quick example:

#!/usr/bin/perl
use strict;
use warnings;

my $scalar;
my @array;
my %hash;

checktype($test);
checktype(@array);
checktype(%hash);

sub checktype {
    my ($obj) = @_;
    if(UNIVERSAL::isa($obj, 'SCALAR')) {
        print "it's a scalar\\n";
    } elsif(UNIVERSAL::isa($obj, 'HASH')) {
        print "it's a hash\\n";
    } elsif(UNIVERSAL::isa($obj, 'ARRAY')) {
        print "it's an array\\n";
    } else {
        print "unknown!!!n";
    }
}

This will output:

it's a scalar
it's an array
it's a hash