Home: Perl Programming Help: Advanced:
Hash of file handles



Jean
User


Apr 3, 2001, 9:42 AM


Views: 2676
Hash of file handles

I'm using a hash of file handles (example follows) and on my machine (ActiveState Perl 5.6.0 build 620) it works perfectly.
The problem is when the same script is run on other machines it reports error.
The question sounds funny, but anyway - is it some version/port specific functionality ?

Just to help understand what's this all about:
The following script writes the contents of the source file to the files named accoding to the first letter of the source file content, e.g. line "victory" will be copied to the file "V.imp"

Code
my $SrcFile   = $ARGV[0] || "users.imp"; 
my $Ext = 'imp';
my $CurLetter = "\0";
my $line;
my %FN; # File Names
my %FH; # File Handles

# Open source file.
open(SRCFILE, "<$SrcFile") or die "Unable to open file $SrcFile\n";
print "Working...\n";
while ( $line = <SRCFILE> ) {
$CurLetter = substr($line, 0, 1);
if ( !defined $FN{$CurLetter} ) {
$FN{$CurLetter} = "$CurLetter.$Ext";
open($FH{$CurLetter}, ">".$FN{$CurLetter}) or die "Unable to open/create target file\n";
}
print {$FH{$CurLetter}} "$line";
}

print "Done.\n";
# Close all.
close;


Jean Spector
QA Engineer @ Extent Technologies, Ltd.
mage@lycosmail.com


seesik
Deleted

Apr 11, 2001, 2:38 PM


Views: 2647
Re: Hash of file handles

you're trying to open with a $FH{$CurLetter}, an undef value. now iirc, 5.6 allows filehandle autovivification, but that won't fly with older releases.
Here's one of many possible solutions...

use Symbol;
...

my $sym = gensym;
open($sym, ">".$FN{$CurLetter}) or die "Unable to open/create target file\n";
$FH{$CurLetter} = $sym;
}
print { *{$FH{$CurLetter}} } "$line";




Jean
User


Apr 11, 2001, 11:42 PM


Views: 2637
Re: Hash of file handles

Thank you very much, seesik.
I did not expect an answer after so many days.
I'm gonna try your "trick".

Jean Spector
QA Engineer @ Extent Technologies, Ltd.
mage@lycosmail.com


seesik
Deleted

Apr 12, 2001, 8:16 AM


Views: 2630
Re: Hash of file handles

np, just FYI, irc is a really helpful resource if you need questions answered ASAP. try #perl on either dalnet or efnet.



Jean
User


Apr 14, 2001, 11:57 PM


Views: 2619
Re: Hash of file handles

10x again, pal.

Jean Spector
QA Engineer @ Extent Technologies, Ltd.
mage@lycosmail.com