CJM CJM - 1 year ago 50
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?

#!/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 Source

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

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


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


print(@nodes . "\n");