in reply to Merging text file

Hi,

Please, allow me add to what has been said.
You might want to avoid using Barewords as filehandles, and also consider using 3 - arugment for open function.
In merging these two text file, Hash can really come in handy here in such format as:

... @hash_data{@first_data} = @second_data; ...
Code below show how the example:
use warnings; use strict; my %std_data; my $std_names = 'names.txt'; my $std_grades = 'grades.txt'; ## call subroutrine read_file, passing different file name @std_data{ @{ read_file($std_names) } } = @{ read_file($std_grades) }; print $_,q{,},$std_data{$_},$/ for sort { $a cmp $b } keys %std_data; sub read_file { my ($file) = @_; my $data = []; open my $fh, '<', $file or die "can't open file:$!"; while ( defined( my $line = <$fh> ) ) { chomp $line; push @{$data}, $line; } close $fh or die "can't close file:$!"; return $data; }
OUTPUT
AARON PITTS,87 CHARLIE DOE,75 DAVID KIM,94
NOTE: Instead of the read_file function used here, there are other module like Tie::File, File::Slurp and other that could be used to get the lines of files into array used more effectively, because I don't know how large your text files are.
Hope this helps.

Replies are listed 'Best First'.
Re^2: Merging text file
by aaron_baugher (Curate) on Sep 06, 2012 at 16:01 UTC

    The larger the files are, the more likely that slurping them into arrays will be a bad idea. Since we have no reason to think that's necessary, and his example keeps them in the same order as fileA (which a hash would lose), it makes more sense to read them line-by-line:

    #!/usr/bin/perl use Modern::Perl; open my $fa, '<', 'file1.txt' or die $!; open my $fb, '<', 'file2.txt' or die $!; while(<$fa>){ chomp; print "$_,", scalar <$fb>; }

    Of course, since he wants a CSV file, he may need to watch out for commas or quoting in his data. If it has none of that, he's safe. If it does, he may be better off building the output file with something like Text::CSV.

    Aaron B.
    Available for small or large Perl jobs; see my home node.

Re^2: Merging text file
by gon770 (Novice) on Sep 06, 2012 at 13:21 UTC
    Thank you so much for the answers :) Have a good day