in reply to File handling in Perl

Here's one way to do it.

use File::Slurp 'read_file'; my @data = map { [ read_file( $_, chomp => 1 ) ] } 'file1', 'file2'; print "$data[0][$_] = $data[1][$_]\n" for 0 .. $#{$data[0]};

perlintro might give you some ideas on how to accomplish it in a more straightforward way. The steps would probably include the following:

Update:

In place of the original solution I posted, this one takes into consideration blank lines, and a trailing newline at the end of the file:

my @data = map { [ read_file( $_, chomp => 1 ) ] } 'file1', 'file2'; print map { length $data[0][$_] ? "$data[0][$_] = $data[1][$_]\n" : '' } 0 .. $#{$data[0]};

...but that starts looking ugly, so here's another alternative:

use File::Slurp 'read_file'; use List::MoreUtils 'pairwise'; print &pairwise( sub { length $a ? "$a = $b\n" : () }, map { [read_file($_,chomp=>1)] } 'file1', 'file2' );

Ultimately all of these probably sacrifice legibility and familiarity in favor of being clever, and that's usually not a good approach. My suggestion is to stick to the steps I outlined in the bullet points.


Dave

Replies are listed 'Best First'.
Re^2: File handling in Perl
by perladdicted (Initiate) on May 26, 2014 at 11:28 UTC
    Thanks for your reply Dave..I have make the script as below: #!/usr/bin/perl -w open (FH, "file1"); $array = <FH>; @array1 = split(/ /, $array); open (FH, "file2"); $array2 = <FH>; @array3 = split(/ /, $array2); $count = 1; while ($count <= @array1){ print "$array1$count - 1 = $array3$count - 1\n"; $count++; } vikky@vikky:~$ perl file.pl a = 10 b = 20 c = 30 d = 40 only problem is last one is not coming correct.Can you please let me know what i'm doing wrong here
      Its fixed missing the chomp.....thanks all