Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Checking if a variable is an array

by Anonymous Monk
on Jun 28, 2007 at 12:35 UTC ( [id://623869]=perlquestion: print w/replies, xml ) Need Help??

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

Hi, I'm trying to parse an XML file using XML::Simple. However, when it creates it's key value pairs it creates arrays where there are many tags with the same name. So for example {Capabilities}->{Layer} could be a single hash or an array of hashes. Is there some way of determining which it is?

Replies are listed 'Best First'.
Re: Checking if a variable is an array
by Corion (Patriarch) on Jun 28, 2007 at 12:41 UTC

    You can check that with the ref function:

    use strict; my $var = [qw(this is an array)]; print ref $var; my $var = "This is a scalar"; print ref $var; my $var = { message => "This is a scalar" }; print ref $var;

    But you really, really want to use the ForceArray configuration parameter to make all your results arrays, whether there is one or more elements in the XML.

      Wow, that's probably the fastest I've ever recieved help! Thanks alot, its solved my problem.
Re: Checking if a variable is an array
by ferreira (Chaplain) on Jun 28, 2007 at 13:35 UTC

    That's a feature of XML::Simple - this difference of behavior between a node which happens once or multiple times. Most of the time, when you expect a node that happen one or more times, you want to tell XML::Simple to always return an array of hashes, so you have a uniform way to deal with the data.

    That's what ForceArray attribute for.

    $data = XMLin( $xml, ForceArray => [ qw(Layer) ] )
    will guarantee that every time Layer is seen, it creates an array (ref).

    Otherwise you'll always have to code something like that:

    my $layers = $data->{Capabilities}->{Layer}; for my $layer ( ref $layers eq 'ARRAY' ? @$layers : ( $layers ) ) { # do something to each Layer }
Re: Checking if a variable is an array
by jettero (Monsignor) on Jun 28, 2007 at 12:39 UTC

    You could do soemthing simple like (ref $var) eq "ARRAY" or something as complicated as Scalar::Util::reftype( $var ) eq "ARRAY". The later is usually only necessary if you're working with blessed scalars.

    I'd be surprised if there wasn't some XML::Simple built-in way to determine how to branch though.

    -Paul

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://623869]
Approved by lidden
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (2)
As of 2024-04-24 17:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found