#Count Items By Dale Swanson June 14, 2012 #takes input from a text file and counts how many times each item appears #one item per line #!/usr/bin/perl my $debug = 1; #debug mode, set to 1 to get lots of output my $inputname = "input.txt"; #filename of the input file my $outputname = "count." . time . ".txt"; #filename of the answer with the unique timestamp added my $sort = 1; #set to 1 to have perl attempt to sort the list of items based on ASCII my $forcelowercase = 1; #set to 1 to force everything into lower case my @filearray; #used to store the contents of the file my $fileline; #used to go through each line in the file #using a trick here to make the first line be a header (COUNT ;ITEM), if the first item in the list is in fact 'ITEM' this will cause problems (to fix just change the string "ITEM" below to nothing ($prevline=""): my $prevline="ITEM"; #the previous line, we'll compare this to file line my $curcount="COUNT"; #count of how many times each item appears open(ifile, "$inputname"); #opens the file with items to be counted @filearray = ; #puts contents in array close(ifile); (@filearray = map { lc } @filearray) if ($forcelowercase); #force to lower case (@filearray = sort(@filearray)) if ($sort); #have perl sort list open(ofile, ">$outputname"); #output the results to a text file foreach $fileline (@filearray) {#go through each line, count each item, when a new item is found output the count of previous one chomp($fileline); #death to newlines if ($fileline eq $prevline) {#same thing means count it $curcount++; } else {#different, means a new item is found my $output = sprintf("%-8s;%s\n",$curcount, $prevline); #formats nicely #%s string, %6s string with 6 spaces, %-6s string with 6 spaces on right (print "$output") if ($debug); print ofile ("$output"); $curcount=1; #reset the count for the new item $prevline=$fileline; #change the previous line, wasn't needed when they were the same } } close(ofile); print "\n\n\n"; (system( 'pause' )) if ($debug);