Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

How can I create an array of filehandles?

( #8874=categorized question: print w/ replies, xml ) Need Help??
Contributed by Punto on Apr 25, 2000 at 07:36 UTC
Q&A  > files


Answer: How can I create an array of filehandles?
contributed by perlmonkey

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++; }
Answer: How can I create an array of filehandles?
contributed by chromatic

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.
Answer: How can I create an array of filehandles?
contributed by CharlesClarkson

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";

or:

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; }

Please (register and) log in if you wish to add an answer



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others scrutinizing the Monastery: (8)
    As of 2015-07-08 00:33 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









      Results (93 votes), past polls