in reply to Re: Write in files
in thread Write in files

The usual way to do this, is to first read the first file into a hash, basically creating a phone directory:

open my $fh, "<", "/root/Desktop/file1.txt"; my %verzeichnis; while (my $line = <$fh>) { $line =~ /RegEx/i; my $telefonnummer = $1; my $name = $2; $verzeichnis{lc $name} = $telefonnummer; } close $fh;

In a second loop (rather than a nested loop) afterwards, you would extract the name from each line, do a lookup in the hash and then write the result to a new file. At the end you can then replace your second file with the new file.

open my $fh2, "<", "/root/Desktop/file2.txt"; open my $new, ">", "/root/Desktop/file2.new"; while (my $line2 = <$fh2>) { chomp $line2; $line2 =~ /RegEx/i; my $name2 = "$1,$2"; print $new $line2; if( defined $verzeichnis{lc $name2} ) { print $new ";+49".$verzeichnis{lc $name2}; } print $new "\n"; } close $fh2; close $new;

Updated a few of typos.

Replies are listed 'Best First'.
Re^3: Write in files
by lolz (Initiate) on Nov 18, 2013 at 10:47 UTC
    I have a few questions to your code. what exactly does the code  $verzeichnis{lc $name} = $telefonnummer; and
    if( defined $verzeichnis{lc $name2} ) { print $new ";+49".$verzeichnis{lc $name2}; }
    does?

    I haven't worked with  defined and  lc yet...

    Thanks for your efforts!

      defined checks whether or not a key is defined in a hash, in this context it will return true if the name was found in your file 1. lc turns a string into lower case, adding a bit of robustness to the code (I assumed you wanted to do case insensitive matching).

      Generally, there is excellent documentation at http://perldoc.perl.org should you be unfamiliar with a specific function.

      UPDATE: It seems I was a bit tired when writing in this thread. While defined does the job, one really should be using exists. Apologies! A simple introduction into hashes can be found here http://www.tutorialspoint.com/perl/perl_hashes.htm but googling "perl hash" will lead to many more good hits.

        what will happen if the define check will be false? The line wouldn't be written to the new file, right?

        what does the Connection from  $Verzeichnis{lc $name2}; exactly do? I want to understand all parts of the script :)