(1) For example:
#!/usr/bin/perl
# wordcount.pl
#
# This program uses wc to count
the numbers of
# characters, words and lines
of any user specified
# file.
#
# by Kwok-Bun Yue
# September 13, 1999
#
use strict;
print "file to count words => ";
my $filename = <STDIN>;
chomp $filename;
my $countline = `wc $filename`;
chomp $countline;
$countline =~ s/^\s*//;
my ($nlines, $nwords, $nchars) = split /\s+/,
$countline;
print "For file $filename:\n",
"
number of characters => $nchars.\n",
"
number of words => $nwords.\n",
"
number of lines => $nlines.\n";
exit 0;
(2) For example:
use strict;
my $var1 = ['This', 'is', 'an', 'example',
'of',
['an', 'array', 'of', {hash => 'yes', array => 'no'}, 0, 1],
{why => 'me', so => ()}, [{}]];
print "total count of var1 => ", itemCount($var1)
, "\n";
my $var2 = 'hi';
print "total count of var2 => ", itemCount($var2)
, "\n";
my $var3 = ();
print "total count of var3 => ", itemCount($var3)
, "\n";
sub itemCount {
my($input) = shift;
my $result = 0; # current
node.
my $i = 0;
if (ref $input) {
if (ref $input
eq "ARRAY") {
for ($i=0; $i < scalar @$input; $i++) {
$result+= itemCount($$input[$i]);
}
}
elsif
(ref $input eq "HASH") {
my @keys = sort keys %$input;
for ($i=0; $i < scalar @keys; $i++) {
$result += itemCount($$input{$keys[$i]});
}
}
}
else {
$result =
1;
}
return $result;
}