Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

How can I create an array of filehandles?

by Punto (Scribe)
on Apr 25, 2000 at 07:36 UTC ( #8874=perlquestion: print w/replies, xml ) Need Help??

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

How can I create an array of filehandles?

Originally posted as a Categorized Question.

  • Comment on How can I create an array of filehandles?

Replies are listed 'Best First'.
Re: How can I create an array of filehandles?
by CharlesClarkson (Curate) on Jun 11, 2001 at 09:35 UTC

    As of Perl 5.6.0 file handles can be autovivified. So it is possible to open a file like this:

    open my $fh, '>', $file_name or die "Cannot open $file_name: $!";

    This allows us to refer to the filehandle as $fh. The following sub returns a hash keyed to the file names:

    my %handles = get_write_handles(qw/col1.txt col2.txt col3.txt/); sub get_write_handles { my @file_names = @_; my %file_handles; foreach (@file_names) { open my $fh, '>', $_ or next; $file_handles{$_} = $fh; } return %file_handles; }

    Note that files that cannot be opened are not defined in the hash. Now the files can be referred to from %handles:

    print { $handles{'in.txt'} } "something\n";


    foreach (values %handles) { print $_ "something\n"; }

    To return an array we need to decide what happens if a file can't be opened. This sub dies:

    sub get_read_handles { my @file_names = @_; my @file_handles; foreach (@file_names) { open my $fh, '<', $_ or die "Yikes $_: $!"; push @file_handles, $fh; } return @file_handles; }

    While this will return undef for failed opens:

    sub get_append_handles { my @file_names = @_; my @file_handles; foreach (@file_names) { if (open my $fh, '>>', $_) { push @file_handles, $fh; } else { push @file_handles, undef; } } return @file_handles; }
Re: How can I create an array of filehandles?
by perlmonkey (Hermit) on Apr 25, 2000 at 08:09 UTC
    The trick is doing someting like:
    open(FILE, "myfile.txt") $file = *FILE
    After that you can use $file as a normal file handle so you can do:
    print $file "Hello File"; close $file;
    So here is how to put it all in an array:
    #!/usr/bin/perl my @filehandles; #make array of 10 file handles for($i=0; $i<10; $i++) { #localize the file glob, so FILE is unique to # the inner loop. local *FILE; open(FILE, ">file$i.txt") || die; #push the typeglobe to the end of the array push(@filehandles, *FILE); } $count=0; #loop through the file handles. # treat $file as a normal file handle foreach $file (@filehandles) { print $file "File $count"; close $file; $count++; }
      You don't need a function do this. You can just:
      open( FILE, "< $file" ) or die( "Bad things happened : $!" ); my $fh = \*FILE; # # Now use $fh as you see fit... # print $fh "Hello, world\n"; # Shouldn't work...FILE was opened RDONLY + :-) $line = <$fh>; do_stuff( $fh ); sub do_stuff { my $fh = shift; print $fh "Whatever...\n"; }
      Hope this helps
      Here's another way of doing this as well ..

      What i'm doing is actually a hash of file handles, but it works the same way .. I'll format this example to use an array. Each part is spread out in individual sections so you can open and close and print anywhere you choose:

      foreach $x (0.. 10) {
         $handles$x = anon_fh()
      # other code here
      # open handles
      foreach $fh (@handles) {
         open ($fh,  "file.txt");
      # code here??
      foreach $fh (@handles) {
      # stuff .. 
         print { $fh } "Text wil do into selected file";
      # stuff
      # more code??
      foreach $fh (@handles) {
         close ($fh);
      sub anon_fh {
         local *FH;
         return *FH;
      Doing print { $handle4 } "Testing" should work to. Something I've learning is that file handles stored in a variable (hash, array, or scalar) needs to be used in a block context {}. I'm not exactly sure why, but problems happen when I don't use the blocks. So I use them. Well.. Just found out that scalars don't have to be in a block, but arrays and hashes do (just did a few perl tests while I was writting this ;). Exact reason why.. I still don't know, I'm just telling you from the errors I got ;) -- philip
        That was actually me (guice) that posted that example.. I appears that this form is dropping my handle :( BTW .. the { $handle4 } is suppose to be: { $handle[4] } .. Appears the form doesn't like [ and ] .. It made a link out of it.. oops ;)
Re: How can I create an array of filehandles?
by chromatic (Archbishop) on Apr 25, 2000 at 18:26 UTC
    With the Symbol module, you can use gensym() to create a new, anonymous typeglob. Since that's the customary way to get at a filehandle, you can do something like this, to create an array of anonymous filehandles:
    #!/usr/bin/perl -w use strict; use Symbol; my @handles; for (1 .. 2) { my $fh = gensym; open $fh, "test$_"; push @handles, $fh; } foreach my $handle (@handles) { print while (<$handle>); print "---\n"; close $handle; }
    In a production environment, I wouldn't use a symbolic reference to a filename like I do in the first loop, but this is just an example.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://8874]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (7)
As of 2023-03-31 19:16 GMT
Find Nodes?
    Voting Booth?
    Which type of climate do you prefer to live in?

    Results (76 votes). Check out past polls.