CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
working with multiple input files

 



oppilif
New User

Jan 18, 2011, 9:20 AM

Post #1 of 3 (267 views)
working with multiple input files Can't Post

Hello,
I'm trying to write my first real perl program and I need to open some files specified on the command line to extract parts of them and merge the information to a new file. The maximum number of files on the command line is 12.
I read on this forum that it could be convenient to use tee to collate all the files and read them as one single file but I wanted to make an array containing all the file contents. How can I do this?

This warning makes me think I'm on the wrong path
Scalar value @content[$i] better written as $content[$i] at ./timelapse.pl line 23.
This is what I wrote:


Code
#!/usr/bin/perl 
use strict;
use warnings;

my $file_number;
my @input_files;

$file_number = $#ARGV;
if ($file_number == -1 || $file_number > 11)
{
die "Usage: timelapse.pl inputfile1.dat inputfile2.dat ... \n";
}

# open files specified on the command line and store handles in the input_files array
my $i;
my @content;
for ($i = 0; $i <= $file_number; $i++)
{
open($input_files[$i], "< $ARGV[$i]") or die "can't open datafile: $!\n";
print "file $ARGV[$i] opened \n";
@content[$i] = <$ARGV[$i]>;
}


Thanks in advance for your help


(This post was edited by oppilif on Jan 18, 2011, 9:21 AM)


BillKSmith
Veteran

Jan 18, 2011, 9:10 PM

Post #2 of 3 (258 views)
Re: [oppilif] working with multiple input files [In reply to] Can't Post

I think you want to store each file in its own array, and then make an array of these arrays. Refer to perldoc perllol for details.


Code
#!/usr/bin/perl  
use strict;
use warnings;
use Data::Dumper;
my @input_files = @ARGV;
verify_usage(@input_files);
my @content;
foreach my $file_name (@input_files) {
open my $FILE, '<', $file_name or
die "Cannot open '$file_name' for input\n";
my @text = <$FILE>;
push @content, [@text];
close $FILE;
}
print Dumper \@content;


sub verify_usage {
my @input_files = @_;
my $number_of_files = @input_files;
if (
($number_of_files == 0) ||
($number_of_files > 12) ||
grep {!/\.dat$/i} @input_files
) {
die "\nUsage: timelapse.pl inputfile1.dat inputfile2.dat ... \n";
}
}

Good Luck,
Bill


oppilif
New User

Jan 18, 2011, 11:52 PM

Post #3 of 3 (252 views)
Re: [oppilif] working with multiple input files [In reply to] Can't Post

Thanks a lot Bill, that was exactly what I meant to do Wink

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives