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

I am working on a project to generate html using a file to acquire the data needed to generate the html. The file contains four data fields. The first three are printed on the html page that is generated and the forth identifies the group to which the first three belong. So the data file looks something like this:
somedata1.........somedata2.........somedata3.......groupid

Each group must be written to a different output file. I want to generate the html files without writing a separate routine for each group. I have created a file with the groupid and it's output file name. I would like to be able to change the filehandle of the output file depending on the groupid as I process the input file. Any help would be greatly appreciated.

Dave

Replies are listed 'Best First'.
Re: Creating multiple output files
by Juerd (Abbot) on Dec 26, 2001 at 03:42 UTC
    From perldata:
    All functions that are capable of creating filehandles (open(), opendir(), pipe(), socketpair(), sysopen(), socket(), and accept()) automatically create an anonymous filehandle if the handle passed to them is an uninitialized scalar variable. This allows the constructs such as "open(my $fh, ...)" and "open(local $fh,...)" to be used to create filehandles that will conveniently be closed automatically when the scope ends, provided there are no other references to them. This largely eliminates the need for typeglobs when opening filehandles that must be passed around, as in the following example:
    sub myopen { open my $fh, "@_" or die "Can't open '@_': $!"; return $fh; } { my $f = myopen("</etc/motd"); print <$f>; # $f implicitly closed here }

    Hope this helps...

    2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Re: Creating multiple output files
by derby (Abbot) on Dec 26, 2001 at 19:05 UTC
    Dave,
    You could always just keep track of the filehandles yourself:

    #!/usr/bin/perl -w use IO::File; use strict; my( %files, $ele1, $ele2, $ele3, $id, $fh ); while( <> ) { ($ele1, $ele2, $ele3, $id ) = split; $files{$id} = $fh = $files{$id} || openup( $id ); print $fh $id, ":\t", $ele1, "\t", $ele2, "\t", $ele3, "\n"; } sub openup { my( $filename ) = shift; my $fh = IO::File->new( $filename, "w" ) || die "unable to open $filename ($!)\n"; return $fh; }

    -derby