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

How can I read the range of two or more text files at once and combine this files for reading.
  • Comment on Read and Combine Range of Two Files (was files)

Replies are listed 'Best First'.
Re: files
by SarahM (Monk) on Jun 13, 2002 at 20:50 UTC
    You can use magic! Just have the first parameter be the file you want to save to, and then just list all the files you want to read from.

    Here is an example

    #!/usr/local/bin/perl my $outfile = shift; # You have to use shift here for magic to work open (OUT, ">$outfile") || die $!; while (<>){ # This is magic, it opens all the files that are on @ARGV print OUT $_; } close (OUT);
    You would call it like this 'myprog.pl outfile file1 file2 file3'
      What if you would have the files been selected from a select menu. Like one dropdown with one file name and another with the other file name using a form to submit the information and display results to the browser window?
        That is different, but it isn't too hard...first, you need to use CGI.pm, then you get a list of the files, open them and write them out to another file. Here is an example...your webform will need one input named 'outfile' for the file you want to save to. You will also need a series of inputs named 'fileX' where 'X' is a number, one for each input file.

        WARNING!!! This example doesn't use taint in order to make it more readable. In a real script you should always use taint.

        use CGI; my $q = new CGI; # Get a CGI object open (OUT, ">$q->param('outfile')") || die $!; # Open our output file my @files = grep{/^file\d+$/} $q->param(); # Grab a list of params for my $filename (@files){ open (IN, $q->param($filename)) || die $!; # Open each input file print OUT <IN>; # Print the input file to the output file close (IN); # Make sure you close the input file } close (OUT);
Re: Read and Combine Range of Two Files (was files)
by bengmau (Beadle) on Jan 02, 2004 at 16:25 UTC
    I want to just combine or append a line to the beginning of a file. Is the processing complexity as low to do the following? open (OUT, ">$q->param('outfile')") || die $!; # Open our output file open (IN, $q->param($filename)) || die $!; # Open each input file print OUT <IN>; # Print the input file to the output file close (IN); # Make sure you close the input file close (OUT); vs. over external command such as: `copy $file1+$file2 fileout`;