Search and replace
funz
created: 2004-06-14 00:16:48
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 = ;
	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);
Re: Search and replace
created: 2004-06-14 00:33:43

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 = ) 
    {
        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...

Re^2: Search and replace
created: 2004-06-14 02:18:59
Im looking for something more simpler than that, since I expect it to be executing every few seconds.
Re^3: Search and replace
BUU
created: 2004-06-14 02:53:37
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.

perlmonks.org content © perlmonks.org and atcroft, BUU, funz

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03