I would read and print every line from the file into a new file, changing the line that matches your first two arguments. If you read the entire file without finding a match then print your new line at the end of your new file. If the new file needs to be in ascending order you can reopen it, sort it, and rewrite it.
d5e5
Practically a Posting Shark
831 posts since Sep 2009
Reputation Points: 162
Solved Threads: 163
Skill Endorsements: 1
You can also do this by tieing your file to an array using Tie::File so any change you make to the array will get written to the file.
#!/usr/bin/perl
use warnings;
use strict;
use Tie::File;
my $filename = 'lookup.txt';
my @lookup;
die "$filename not found" unless -e $filename;
tie @lookup, 'Tie::File', $filename or die "Failed to tie $filename: $!";
edit_file('InstanceName1','DomainName2','Server5'); #Edit existing record
edit_file('InstanceName8','DomainName2','Server999'); #Add new record
untie @lookup; # all finished
sub edit_file{
my ($iname, $dname, $sname) = @_;
my $found = 0;
foreach my $rec (@lookup){
chomp $rec;
my @keyarray = split(/::/, $rec);
if ($keyarray[0] . $keyarray[1] eq $iname . $dname){
$found++;
$rec = join('::', $iname, $dname, $sname);
}
}
if ($found == 0){
push @lookup, join('::', $iname, $dname, $sname);
}
}
d5e5
Practically a Posting Shark
831 posts since Sep 2009
Reputation Points: 162
Solved Threads: 163
Skill Endorsements: 1