Because the first parameter passed to open is the file handle.  In the first case, there are 3 file handles: 1,2,3.  In the second case, the same file handle is used for each file, always ‘1’.

 


From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Hugh Loebner
Sent: Friday, July 01, 2005 9:21 AM
To: Perl-Win32-Users Mailing List; activeperl@listserv.ActiveState.com
Subject: Why is this a problem?

 

Hello perl gurus,

I spent almost a whole day solving this problem.  However, I wonder why it's a problem.

# ////////////////////////////////////////////////////
use strict;
no strict "refs" ;

# this works fine, produces three files, aa , bb, cc with contents 'xxx aa xxx' etc

my    %fh = ( aa => 1, bb =>2, cc => 3) ;  # note that each instance of $fh{$fhkey} has a different value

foreach my $fhkey ( keys %fh){
    open  ( $fh{$fhkey}, ">$fhkey" )  ;   
}
               
foreach my $fhkey ( keys %fh ){
    print { $fh{$fhkey} }  "xxx $fhkey xxx \n" ;    # note file handle $fh{$fhkey} has to be in a block
} ;

foreach my $fhkey ( keys %fh ){
    close $fh{$fhkey} ;   
}

#------------------------------------------------------------
# The following program (which is what I started out with) will NOT work properly:  Each element of %fh has a value of 1
# Why doesn't this work properly?  - all statements write to one file
#------------------------------------------------------------


my    %fh = ( aa => 1, bb =>1, cc => 1) ;    # note - only change, each $fh{} has value of 1

foreach my $fhkey ( keys %fh){
    open  ( $fh{$fhkey}, ">$fhkey" )  ;   
}
               
foreach my $fhkey ( keys %fh ){
    print { $fh{$fhkey} }  "xxx $fhkey xxx \n" ;    # note file handle $fh{$fhkey} has to be in a block   
} ;

foreach my $fhkey ( keys %fh ){
    close $fh{$fhkey} ;   
}

# ////////////////////////////////////////////////////
Hugh Loebner

_______________________________________________
Perl-Win32-Users mailing list
Perl-Win32-Users@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to