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;
|