Aaron C. de Bruyn <mailto:[EMAIL PROTECTED]> wrote:

: In the Perl documentation (perlintro) it says that you can find out
: the number of elements in an array using the following syntax:
: 
: print $myvar[$#mmyvar];

    No. That prints the value of the last element of @myvar. The number
items in the array is the scalar evaluation of @myvar.

print scalar @myvar;


: I am running into a problem when I try to find the number of elements
: in an array that is being returned from an object.
: 
: I am using XML::Simple to parse an XML document, and have the
: following snippet of code giving me trouble:
: 
: print $#xml->{'channel'};

    $xml is not an array. It is (most likely) an object. Adding # is not
useful. If $xml->{channel} is an array reference then the total elements
are printed below. Since 'print' uses list context we need to specify
scalar context.

print scalar @{ $xml->{channel} };


: for ($i=0; $i <= $#xml->{'channel'}; $i++) {
:         print $xml->{'channel'}[$i];
: }

    In perl, we usually can iterate an array without using its indices.

foreach my $channel ( @{ $xml->{channel} } ) {
    print $channel;
}

OR:

print @{ $xml->{channel} };


HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
254 968-8328


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to