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

Dear Monks,

I would like to concatene data from two files (excel csv files). However, I would like to concatene only a part of them.

I have two files.

Name_1;Name_2 1;2 3;4
Name_1;Name_2 5;6 7;8

I have made the script

use strict; use diagnostics; use warnings; my $infile; my @FILES = glob('file_*'); my $outfile = "outfile.csv"; open(OUTFILE, ">$outfile"); foreach $infile(@FILES){ open(INFILE, "<$infile"); while (my $line = <INFILE>){ print OUTFILE $line; } close INFILE; } close OUTFILE;

The result is:

Name_1;Name_2 1;2 3;4 Name_1;Name_2 5;6 7;8

I would like to have only

Name_1;Name_2 1;2 3;4 5;6 7;8

Could you give me some advice ? Thanks a lot

Replies are listed 'Best First'.
Re: data concatenation in an output file
by moritz (Cardinal) on Jan 25, 2008 at 14:55 UTC
    Print the first two lines of a file only if you are in the first file.
    if ($. <= 2){ if ($infile eq $FILES[0]){ print OUTFILE $line; } } else { print OUTFILE $line; }

      or you could reduce the clutter a little by:

      print OUTFILE $line unless $. <= 2 and $infile ne $FILES[0];

      Perl is environmentally friendly - it saves trees
Re: data concatenation in an output file
by jwkrahn (Abbot) on Jan 25, 2008 at 19:19 UTC

    You could try it like this:

    use strict; use diagnostics; use warnings; @ARGV = glob 'file_*'; my $outfile = 'outfile.csv'; open my $OUTFILE, '>', $outfile or die "Cannot open '$outfile' $!"; while ( <> ) { if ( eof && !eof() ) { <>;<>; } print $OUTFILE $_; } close $OUTFILE;