User Tools

Site Tools


tutorials:perl:count_first_name.pl
count_first_name.pl
# count_first_name.pl
# Read an input file that contains several names 
# (assuming one name in each line, the first name 
# and the last name are separate by a space). 
# Count how the number of times each first name appeared 
# in the input. Print the result to STDOUT, 
# sort the names alphabetically.
 
my $in_file = shift;
 
my %count_hash; # key = first_name, value = count
 
open IN, "<$in_file";
while ( my $line = <IN> ) {
	chomp $line;
	my ( $first_name, $last_name ) = split /\s/, $line;
	$count_hash{$first_name}++;
}
close IN;
 
foreach my $first_name ( sort { $a cmp $b } keys %count_hash ) {
	print "$first_name appeared $count_hash{$first_name} times\n";
}
tutorials/perl/count_first_name.pl.txt · Last modified: 2012/06/15 00:36 by chkuo