RobertCraven has asked for the wisdom of the Perl Monks concerning the following question:

Wise Monks,

I need enlightenment how to figure out if a variable is an array.
Using XML::Simple, I am parsing a SwissProt XML file. My concern is about their 'accession' elements, it can be one or more:
<accession>P41933</accession>
or
<accession>P41932</accession> <accession>Q21537</accession>
XML::Simple returns an array if there is more than one element and an scalar if only one.
In case of an array, I'd like to store the first element, else just the element.
Is there any way to test if a variable contains an array? Something like:
my $id; if(@{$HRdata->{'entry'}->{'accession'}}){ $id = $HRdata->{'entry'}->{'accession'}->[0]; } else{ $id = $HRdata->{'entry'}->{'accession'}; }
If of interest, the XML files can be viewed here:
http://www.uniprot.org/uniprot/P41932.xml
http://www.uniprot.org/uniprot/P41933.xml

Many thanks!

Replies are listed 'Best First'.
Re: check if variable is an array
by moritz (Cardinal) on Jan 31, 2009 at 18:36 UTC
    If you call XML::Simple with ForceArray => [qw(accession)], then it will always be an array, and you don't need such a check in your code.
Re: check if variable is an array
by toolic (Bishop) on Jan 31, 2009 at 18:09 UTC
    Did you try ref?

    Otherwise, show how you are calling XML::Simple methods.

      Perfect, thanks so much!