CJM CJM - 6 months ago 8
Perl Question

how do I print the number of elements

following is my code which will return name of the units.
but how do I count and print the number of units using perl?
basically printing the number of elements which contains unit tag?
Thanks.

#!/usr/bin/perl -w
use strict;
use XML::DOM;

my $parser = new XML::DOM::Parser;
my $dom_obj;

die "Unable to parse XML document\n"
unless $dom_obj = $parser->parsefile("course.xml");

my @nodes = $dom_obj->getElementsByTagName("unit");

foreach my $elem (@nodes)
{
if ($elem->getNodeType == ELEMENT_NODE)
{
print $elem->getTagName, "\n";
}

}

Answer

To find the number of elements in an array, evaluate the array in scalar context.

print(scalar(@nodes), "\n");

or

print(0+@nodes, "\n");

or

print(@nodes . "\n");