perladdicted has asked for the wisdom of the Perl Monks concerning the following question:

Hello Experts, I'm trying to print two files and the output should be get as below: file1 = a b c d file2 = 10 20 30 40 output: a = 10 b = 20 c = 30 d = 40 Can anyone please help me how can i get this output

Replies are listed 'Best First'.
Re: File handling in Perl
by davido (Cardinal) on May 20, 2014 at 07:23 UTC

    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:

    • Open both input files with unique filehandles.
    • Using a while loop, iterate over the file that contains identifiers.
    • Inside the loop, read a line from the file that contains values.
    • Chomp the identifier line.
    • Print the current identifier, and the current value, with a " = " between them.
    • Continue to the next iteration.

    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

      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
Re: File handling in Perl
by marto (Cardinal) on May 20, 2014 at 07:05 UTC