in reply to Strange Behavior with XML::Simple when pulling info out of an XML file

lunchlady55:

I bet if you used strict and warnings, you'd have a message from perl telling you about the undeclared variable @datasource. I'm guessing that since you're getting 0, telling you it's empty. You're using a different variable ($datasource) in your for loop.

...roboticus

Replies are listed 'Best First'.
Re^2: Strange Behavior with XML::Simple when pulling info out of an XML file
by lunchlady55 (Initiate) on Nov 27, 2010 at 00:28 UTC

    OK, if anyone else stumbles upon this page, here's what I came up with...Apparently, $datasource is a reference to an array. So you can't just change the $ to an @. You have to use curly braces like this to read into the reference:

    $element = scalar(@{$datasource});

    My code now reads:

    1 #!/usr/bin/env perl 2 3 use strict; 4 use warnings; 5 #use IO::Socket; 6 use Data::Dumper; 7 use XML::Simple; 8 my $xs1 = XML::Simple->new(); 9 my $file = $ARGV[0]; 10 my $doc = $xs1->XMLin($file, forcearray => 1); 11 foreach my $datasource ($doc->{DATASOURCE}){ 12 my $length = scalar(@{$datasource}); 13 print $length ."\n"; 14 foreach my $element (@{$datasource}){ 15 print Dumper($element); 16 # my $element = scalar(@datasource); 17 # print "Element = $element\n"; 18 # for(my $element=0; $element < scalar($datasource); $element++){ 19 # print $datasource[$element]; 20 } 21 }

    Each $element is a reference to a hash now. I'll have to de-reference those to access them as well, I'm sure.

      In most languages, you can only use an identifier in one context - not so in Perl! You can have $x (scalar), @x (array), %x (hash), sub x{...} all in the same program. So $x is a completely unrelated thing to @x. As you have correctly surmised, the value of an array evaluated in a scalar context is the length of that array.

      $element = scalar(@{$datasource});
      $element = @$datasource; #same thing $element is a scalar so explicit conversion not required.
      $x < @$datasource #also scalar context
      You only need the extra curly braces when there is a subscript involved - so deference applies to the whole thing.