Using a variable file-handle

Dan.Sherer at wellpoint.com Dan.Sherer at wellpoint.com
Wed Mar 15 16:53:00 CST 2000


Here's an interesting technique that another Perl programmer showed me today:

Using the type of data to control a file.



Scenario:  You have an input file that you are processing and when you get
ready to output, records go into different files based upon the contents of
some part of the record.

My first thought was just to have an "if" statement and multiple "print"
commands, one per file handle.  But Sally realized that you only need one!
In this example, I'll replace the full input file with a tiny list and leave
out  the other processing for the sake of brevity.


open(vdn, "> vdn.txt") || die "Cannot create vdn.txt: $!\n";
open(spl, "> spl.txt") || die "Cannot create spl.txt: $!\n";

@data = qw( vdn spl xxx);    # dummy input data for this example only

foreach $type (@data) {      # in the real program, this is a "while (<INPUT>)
{" statement
        unless ($type =~ (/(spl|vdn)/)) {
                print "Bad record type '$type' detected\n";
                next;
        }
        print $type "This is a $type record\n";
}


Quite cool, and very "perlish".


Daniel



More information about the Thousand-oaks-pm mailing list