#!/usr/bin/perl
use strict; # get perl to warn us if we try to use an undeclared variable.
# get all words on first line, and store them in a hash
#
# note: it doesn't matter which line we get the word list from because
# we only want to know if all lines have the same number of identical
# words.
my %words = map { $_ => 1 } split (/\s+/,<>);
while(<>) {
# now do the same for each subsequent line
my %thisline = map { $_ => 1 } split ;
# and compare them. exit with a non-zero exit code if they differ.
if (%words != %thisline) {
# optionally print a warning message to STDERR here.
exit 1;
}
};
# print the number of words we saw on the first line
print scalar keys %words, "\n";
exit 0
(the exit 0
on the last line isn't necessary - that's the default anyway. It's "useful" only to document that the return code is an important part of this program's output.
NOTE: this won't count duplicate words on a line. e.g. sda sdb sdc sdc sdc
will count as 3 words, not 5 because the last three words are the same. If that's significant, the hashes should also count the number of times each word appears. Something like this:
#!/usr/bin/perl
use strict; # get perl to warn us if we try to use an undeclared variable.
# get all words on first line, and store them in a hash
#
# note: it doesn't matter which line we get the word list from because
# we only want to know if all lines have the same number of identical
# words.
my %words=();
$words{$_}++ for split (/\s+/,<>);
while(<>) {
# now do the same for each subsequent line
my %thisline=();
$thisline{$_}++ for split;
# and compare them. exit with a non-zero exit code if they differ.
if (%words != %thisline) {
# optionally print a warning message to STDERR here
exit 1;
}
};
# add up the number of times each word was seen on the first line
my $count=0;
foreach (keys %words) {
$count += $words{$_};
};
# print the total
print "$count\n";
exit 0;
The significant difference is the way that the hashed arrays are populated. In the first version, it just sets the value for each key ("word") to 1. In the second, it counts the number of times each key is seen.
The second version also has to add up the values for each key, it can't just print the number of keys seen.