[Israel.pm] Unreference file scalar

Shmuel Fomberg semuelf at 012.net.il
Thu Sep 20 09:50:51 PDT 2007

Yuval Yaari wrote:

>> Perl kept this $fh alive because it is selected,
>> but its reference count get decreased to zero.
>> And when it's time for global destruction, Perl finds this file and
>> discover
>> that it has zero references.
>Of course, you declared it as my $fh, remember? :)
>After the eval block thingie, its refcount should be decreased.

Well, no. select should (and probably normally do) keep a reference to that
file handle, and in the end of the program the ref_count of that scalar
should be one, not zero. 
See the code below that is pure Perl, and serve as an example.

So the bug is really this: 'select' does not (always) increase the ref_count
of the selected file handle.


######## Begin Code
use strict;

open my $verify, "<", "temp1.txt" or die "oops";
print STDERR <$verify>;
close $verify;

sub step1 {
   open my $fh, ">", "temp1.txt" or die "oops";
   select $fh;
sub step2 {
   open my $new_fh, ">", "temp2.txt" or die "oops";
   my $old_fh = select $new_fh;
   print $old_fh "did I?\n";
   close $old_fh;
########## End Code 

More information about the Perl mailing list