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

Ok ---
I humbly ask for your patience and wisdom.
Earlier I posted the question regarding how to close multiple filehandles in one line.
I got some excellent and exceptionally helpful replies.
Now I must ask the reverse: Surely there most be a way, based on the multiple closure replies that would simplify, most likely not a one-liner, the code below:
my $OUT1 = new FileHandle; open($OUT1,">$filename1"); my $OUT2 = new FileHandle; open($OUT2,">$filename2"); my $OUT3 = new FileHandle; open($OUT3,">$filename3"); my $OUT4 = new FileHandle; open($OUT4,">$filename4");
Thanks for your help!

Replies are listed 'Best First'.
Re: Opening Multiple FileHandles w/ Simpler Code
by Zaxo (Archbishop) on Aug 09, 2005 at 18:58 UTC

    You can open them in a loop or map, filling an array or hash with references to the handles.

    my @handles = map {FileHandle->new("> $_")} @filenames; $handles[3]->print( 'Message to the fourth handle.', $/); $_->print('Message to all handles', $/) for @handles;

    After Compline,
    Zaxo

      Absolutely Brilliant! Perfection! Thanks!

        Just keep in mind that certain constructs, such as < > do not accept lexical handles unless they are in "simple" variables. E.g.

        while ( <$handles[ 3 ]> ) { # do something with last line read }
        won't work. You need to do something like this:
        while ( defined( my $line = $handles[ 3 ]->getline ) ) { # do something with $line }
        or
        frobnicate( $handles[ 3 ]->getline ) until $handles[ 3 ]->eof;
        or, if you really prefer to avoid invoking methods on then handle, the you can do this
        my $tmp = $handles[ 3 ]; while ( <$tmp> ) { # go crazy }

        the lowliest monk

Re: Opening Multiple FileHandles w/ Simpler Code
by merlyn (Sage) on Aug 09, 2005 at 19:18 UTC