Useful Perl

Ever want to have a simple script/program that:

  1. takes a few arguments
  2. reads in a text file
  3. checks to see if the arguments are already in the text file
  4. if they are add them, if not die?

If yes, then you might find the following little snippet of perl i hacked up for work useful:

 
my %values = ();
my @strs = ();
 
open DATA, "<test.txt";
 
while(<DATA>) { 
    	chomp; 
	@parts = split ':', $_;
	$parts[0] =~ s/^\s+|\s+$//g;
	$parts[1] =~ s/^\s+|\s+$//g;
	if ($parts[0] eq $ARGV[0]) { die "Already in List\n"; }
	$values{ $parts[0] } = $parts[1];
}
 
$values{$ARGV[0]} = $ARGV[1];
 
close DATA;
 
open DATA, ">test.txt";
 
for my $x ( sort keys %values ) {
	printf DATA "%11s: %s\n",$x,$values{$x};
}
 
close DATA;
 

Leave a Reply

Your email address will not be published. Required fields are marked *