CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



Jean
User


Apr 3, 2001, 9:42 AM

Post #1 of 5 (1396 views)
Hash of file handles Can't Post

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

Post #2 of 5 (1367 views)
Re: Hash of file handles [In reply to] Can't Post

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

Post #3 of 5 (1357 views)
Re: Hash of file handles [In reply to] Can't Post

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

Post #4 of 5 (1350 views)
Re: Hash of file handles [In reply to] Can't Post

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

Post #5 of 5 (1339 views)
Re: Hash of file handles [In reply to] Can't Post

10x again, pal.

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

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives