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

hello. I need to open x number of files and assign them to arrays. is there code to create array1, array2, and so on to correspond to the files, without manually naming each one. if its an array of arrays how do I create one. thanks everybody, i ended up using a hash of hashes and it works fine so far.

Replies are listed 'Best First'.
Re: naming multiple arrays
by VSarkiss (Monsignor) on Jun 05, 2006 at 17:54 UTC
Re: naming multiple arrays
by rational_icthus (Sexton) on Jun 05, 2006 at 18:02 UTC
    I think we need a bit more information on your specific case. Do you want to store the filehandles into the array of arrays, or would your prefer to store the actual file contents? Remember that if you are working with large files and you store the entire file into the array, you're talking about utilizing a great deal of memory.

    If these are text files, I'd choose a hash of filehandles. If you had fully-qualified paths to all your files in the array @files, I'd do something like this:

    my %filehandles; open $filehandles{$_}, $_ for @files;
    Then you can work with each individual filehandle as you wish, and everything is indexed by the file's name. Note that this is only one solution. There are lots of ways to approach this question.
Re: naming multiple arrays
by derby (Abbot) on Jun 05, 2006 at 17:47 UTC
Re: naming multiple arrays
by ahmad (Hermit) on Jun 05, 2006 at 18:43 UTC

    why would you need to open x number of files and store each file content into array ?

    depending on how many files you want to open and how large each file is ,

    you may end up using alot of memory ( you may run out of memory also )

    there's more than one way to do anything ,

    tell us what you want to accomplish you may get a better answer ;)

Re: naming multiple arrays
by sgifford (Prior) on Jun 05, 2006 at 19:36 UTC
    What you probably want to do is create an array of arrays, or else a hash of arrays. Something like:
    our @array; our %hash; my $i = 0; foreach my $f (@ARGV) { open(F,"< $f") or die "Couldn't open '$f': $!\n"; my @lines = <F>; # This is how to store the lines into an array $array[$i] = \@lines; # And this is how to store them into a hash. $hash{"array$i"} = \@lines; $i++; }
Re: naming multiple arrays
by xorl (Deacon) on Jun 05, 2006 at 19:46 UTC
    As mentioned above you should try and change your script so that you don't risk running out of memory. However if you really want to do this, here is one example taken from perlfunc:open
    # process argument list of files along with any includes foreach $file (@ARGV) { process($file, 'fh00'); } sub process { my($filename, $input) = @_; $input++; # this is a string increment unless (open($input, $filename)) { print STDERR "Can't open $filename: $!\n"; return; } local $_; while (<$input>) { # note use of indirection if (/^#include "(.*)"/) { process($1, $input); next; } #... # whatever } }