Search code examples
perlfilehandle

How can I generate several Perl filehandles programmatically?


Is there any way in Perl to generate file handles programmatically?

I want to open ten files simultaneously and write to them by using file handle which consists of (CONST NAME + NUMBER). For example:

 print const_name4  "data.."; #Then print the datat to file #4

Solution

  • You can stick filehandles straight into an uninitialised array slot.

    my @handles;
    for my $number (0 .. 9) {
        open $handles[$number], '>', "data$number";
    }
    

    Don't forget that the syntax for printing to a handle in an array is slightly different:

    print $handles[3] $data;    # syntax error
    print {$handles[3]} $data;  # you need braces like this