in reply to Arrays of files from an array of file names

Heh! I recognise some of that code :) _And_ you're planning to use one of my modules to do the array comparison.

In general, if you have a list of filenames and want to get a list of file contents then you'd better be sure that the files are small or you've got a lot of memory! That being said, you can do it like this:

my @files = qw(file1 file2 file3); my @contents; foreach (@files} { open FILE, $_ or do { warn "Can't open $_: $!\n"; next } local $/; push @contents, <FILE>; }

This gives you each file's contents in a scalar. To get an array of each file's contents you'd do this:

my @files = qw(file1 file2 file3); my @contents; foreach (@files} { open FILE, $_ or do { warn "Can't open $_: $!\n"; next } push @contents, [<FILE>]; }
--
<http://www.dave.org.uk>

"Perl makes the fun jobs fun
and the boring jobs bearable" - me

Replies are listed 'Best First'.
Re: Re: Arrays of files from an array of file names
by Tuna (Friar) on Feb 18, 2001 at 19:56 UTC
    Thanks for pointing out a very simple concept that I was overlooking completely. I was thinking that I needed to write each individual file to it's own array, for comparison 1 file at a time. Yeah, why not write all of the "non-beginning" files to one array!!! BTW, yes, the file sizes are very small; usally between 9k - 11k. Thanks for all of your help, as well as providing me (and others) with Array::Compare.


    Steve
What am I doing wrong?
by Tuna (Friar) on Feb 19, 2001 at 06:58 UTC
    I do NOT want to sound ingrateful.....but, I'm trying your code and failing miserably.:
    #!/usr/bin/perl -w use strict; my $file1 = "trixee"; #just some nicknames! my $file2 = "limo"; my $file3 = "nata"; my @files = qw(file1 file2 file3); my @contents; foreach (@files) { open FILE, $_ or do { warn "Can't open $_: $!\n"; next } push @contents, [<FILE>]; } foreach my $tmp(@contents) { print "$tmp\n"; }
    This fails with:

    "syntax error at ./testsub.pl line 16, near "push"
    "Execution of ./testsub.pl aborted due to compilation errors".

    Any ideas?
      First, are you sure @files isn't supposed to be ($file1, $file2, $file3)? Right now, you're just setting it to the STRINGS ('file1', 'file2', 'file3').

      Anyway, you're missing the semicolon at the end of the do BLOCK expression on line 14. do BLOCK turns a BLOCK (which DOESN'T need a semicolon at the end) into an expression.

      And you can get away from that by doing:
      open FILE, $_ or warn("...: $!"), next;


      japhy -- Perl and Regex Hacker