Please sir, write my code.
April 29, 2004 5:01 PM
Subscribe
Any MeFi perl/cgi programmers feel like writing a few lines of code?
I need to add a function to an existing script, which looks like a piece of cake if you know perl.
Given a $newstring and a file of records, each consisting of a count and a string delimited by a space:
201 this.thing
23 that.thing
14 someother.thing
...
I need a function to check whether $newstring already exists in the file. If so, increment the count. If not, add a new record to the file with a count of 1. Finally, sort the file in descending order by count.
Maybe 5 minutes for you. Learning perl first for me. If it would be easier with fixed length counts like 0000201, that is fine, too.
If this is inappropriate for Ask MeFi, my apologies. I'll take it over to answers.google.
posted by Geo to computers & internet (10 comments total)
# the input string - this just gets it from the command line
$newstring = $ARGV[0];
# temp variables
my $found = 0;
my @lines;
# open filename.txt for reading
open FILE, "<filename.txt";
# for each line in the file
while (<FILE>) {
# on any line with a number, a space, and $newstring, increment the number, and remember that we found it
if (s/^(\d+)(?=\s+$newstring)/$1 + 1/e) {$found = 1;}
# add this line to our array of lines
push @lines, $_;
}
close FILE;
# if we didn't find it, make the new line
if (!$found) {
push @lines, "1 $newstring\n";
}
# sort the lines
@lines = sort {int($a) <=> int($b)} @lines;
# open the same file for writing
open FILE, ">filename.txt";
# write out each line to the file
for (@lines) {print FILE;}
close FILE;
posted by whatnotever at 5:51 PM on April 29, 2004