I need a perl function that will check the following in a file, modify if only the first two columns match , and if not found in the file, insert the values.

The file is like below


The perl function needs to match the instance name, domain name, and check if the servername is the same , else replace the server name, and after iterating through the file, if the string is not found, insert the same into the file. The stub function i have written explains the same.

sub functionname()
        my $lookupfile = "lookupfile";
        open(MAPPING,"<$lookupfile") || die $!;

                chomp $key;
                my @keyarray =split(/::/,$key);
                $cusName= $keyarray[0];
                $apmName= $keyarray[1];
                $host= $keyarray[2];
                $skey= $cusName."::".$apmName;
                $sskey= $var1."::".$ipName;
                if ( ! -z $cusName && ! -z $apmName )
                    if ( $cusName eq $var1 )
                        if ( $skey eq $sskey )
                            if ( $host eq $var3 )
                                print "present";
                                print $cusName."::".$apmName."::".$host;
                                print $var1."::".$var2."::".$var3;
                                ## replace first with second

        if ( $presentflag == 0 )
            # insert into the file $var1,$var2,$var3 as $var1::$var2::$var3


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.

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.

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){
            $rec = join('::', $iname, $dname, $sname);
    if ($found == 0){
        push @lookup, join('::', $iname, $dname, $sname);
commented: Thanks +0