in reply to updating file

Here's an explicit method:

my $newcolor = 'purple'; my $seen = 0; open my $infile, "<", 'colorfile.txt' or die "Can't open color file for reading.\n$!"; while ( my $color = <$infile> ) { $seen++ if $color =~ /$newcolor/; } close $infile; unless ( $seen ) { open my $outfile, ">>", 'colorfile.txt' or die "Can't open the color file for append.\n$!"; print $outfile "$newcolor\n"; close $outfile or die "Couldn't close the output file.\n$!"; }

And here's a grep method:

my $newcolor = 'purple'; open my $infile, "<", 'colorfile.txt' or die "Can't open color file for input.\n$!"; my $seen = grep { /$newcolor/ } <$infile>; close $infile; open my $outfile, ">>" 'colorfile.txt' or die "Can't open color file for output.\n$!"; print $outfile "$newcolor\n" unless $seen; close $outfile or die "Can't close the output file.\n$!";

You could also just open the file once, for read/write access, but that can get a little confusing if you don't do it right. See perlopentut for details.

The above methods just open the file for reading, scan through it to see if the color exists. If it doesn't, reopen the file for appending, and append the new color to the file.

Update: Here's another solution that uses Tie::File. It doesn't scale as well, it's definately convenient:

use strict; use warnings; use Tie::File; my $newcolor = 'purple'; tie my @array, 'Tie::File', 'colorfile.txt' or die "Can't tie color file.\n$!"; push @array, "$newcolor\n" unless grep { /$newcolor/ } @array; untie @array;


Dave

Replies are listed 'Best First'.
Re: Re: updating file
by sgifford (Prior) on Apr 15, 2004 at 20:59 UTC
    A nit...these scripts won't update the file if $newcolor is a substring of a color already in the file. For example if the file has:
    red-orange bluegreen
    and you try to add one of the colors red, blue, or green, your script won't add it.

    The regexp should probably be anchored and chomp used:

    chomp($color); $seen++ if $color =~ /^$newcolor$/;
    or eq could be used instead:
    chomp($color); $seen++ if $color eq $newcolor;