Perl script for Calling a function and writing all its contents to a file

I have a function which does awk proceessing

sub mergeDescription {
        system (q@awk -F'~' '
        NR == FNR {
                A[$1] = $1
                B[$2] = $2
                C[$1,$2] = $0
                next
        }
        {
                n = split ( C[$1,$3], V, "~" )
                if ( A[$1] && B[$3] )
                        print $0, V[n]
                else
                        print $0,"UNDEFINED"
        } ' OFS="~" file1 file2@);
}

I want to write all the output generated by this function to a file. Please suggest.

  1. Please use code tags, mate. Your code looks garbled.
  2. It's not a good practice to invoke awk in a system call from perl, when you can do all of that (and much more) from perl itself. So, what is that you want to achieve? (Please provide input files, logic, desired output)

Hi,
I have 2 files of below format.

File1

AA~1~STEVE~3.1~4.1~5.1
AA~2~DANIEL~3.2~4.2~5.2
BB~3~STEVE~3.3~4.3~5.3
BB~4~TIM~3.4~4.4~5.4

File 2

AA~STEVE~AA STEVE WORKS at AUTO COMPANY
AA~DANIEL~AA DANIEL IS A ELECTRICIAN
BB~STEVE~BB STEVE IS A COOK

I want to match 1st and 3rd column values of file 1 against 1st and 2nd column values of file2. If both match conditions satisfy then i want to print 3rd column of file2 at the end of file1.

If not then print "UNDEFINED" at end of file 1

Below is the expected output which i want to print in file1

AA~1~STEVE~3.1~4.1~5.1~AA STEVE WORKS at AUTO COMPANY
AA~2~DANIEL~3.2~4.2~5.2~AA DANIEL IS A ELECTRICIAN
BB~3~STEVE~3.3~4.3~5.3~BB STEVE IS A COOK
BB~4~TIM~3.4~4.4~5.4~UNDEFINED JOB

I created a function to fetch the data but now i am not able to write its output to a file

sub mergeDescription {
        system (q@awk -F'~' '
        NR == FNR {
                A[$1] = $1
                B[$2] = $2
                C[$1,$2] = $0
                next
        }
        {
                n = split ( C[$1,$3], V, "~" )
                if ( A[$1] && B[$3] )
                        print $0, V[n]
                else
                        print $0,"UNDEFINED"
        } ' OFS="~" file1 file2@);
}

Please suggest

sub mergeDescription {
    open F1, "< file1";
    open F2, "< file2";
    
    my (%hash);
    
    while (<F2>) {
        chomp;
        (/([^~]*~[^~]*)~(.*)/) && ($hash{$1} = $2);
    }
    
    while (<F1>) {
        chomp;
        my @fields = split /~/;
        
        if (exists($hash{"$fields[0]~$fields[2]"})) {
            print join ("~", @fields), "~", $hash{"$fields[0]~$fields[2]"}, "\n";
        }
        else {
            print join ("~", @fields), "~UNDEFINED JOB\n";
        }
    }
    
    close F2;
    close F1;
}