funz has asked for the wisdom of the Perl Monks concerning the following question:

I have a flat file with a list of element, they are seperated by a new line (\n) and each line is also seperated by a &, example "4&1028x768". The code below works, it searches the file, when it finds a match (1028x768) it increments the count, deletes the original and adds the updated count at the end of the file. What I need to do is, if it doesn't find a match then it will add a new entry at the end of the file, ex. 1&800x600.
open (DATA,"$resolution"); @data = <DATA>; close(DATA); $data = "@data"; $data=~ m/.*&$FORM{'res'}\n/i; ($count, $res) = split(/&/, $&); @add = grep{ !(/.*&$res\n/i) } @data; $count++; push(@add, "$count&$res\n"); open (DATA,">$resolution"); print DATA @add; close(DATA);

Replies are listed 'Best First'.
Re: Search and replace
by atcroft (Abbot) on Jun 14, 2004 at 04:33 UTC

    This seems like a good place to use a hash. If I am understanding you properly, your data format is:

    count&key
    count&key
    

    In such a case, it seems as if you would want to read each line, loading them into a hash, then write them back out. Something along the following lines might work, in such a case:

    my (%dhash); # Lines assumed to be in @data, adapted from OP's code. open(DATA, $resolution) or die("Can't open $resolution for input: $!\n"); while (my $line = <DATA>) { my @parts = split(/&/, $line); if (exists($dhash{$parts[1]})) { $dhash{$parts[1]} += $parts[0]; } else { $dhash{$parts[1]} = 1; } } close(DATA); # Sample dump routine. open(DATA, '> ' . $resolution) or die("Can't open $resolution for output: $!\n"); foreach my $k (sort(keys(%dhash))) { printf DATA "%d&%s\n", $dhash{$k}, $k; } close(DATA);

    Hope that helps...

      Im looking for something more simpler than that, since I expect it to be executing every few seconds.
        Have you tried it? Do you know how fast it runs? Do you know how fast it has to be? Simplicity rarely has much to do with speed.