Odd (undocumented?) behavior of RAM file within a loop



Greetings. I am writing a program which processes some files within a loop, and I am using the ability (as of Perl 5.8) to open a filehandle on a scalar reference (which I recycle in the loop). Kindly consider this stripped-down trivial code example which illustrates my question:

#!/usr/bin/perl
use strict; use warnings;

foreach (1..3) {
warn "Pass #$_\n";
my $file_in_memory;
open(my $fh, '>', \$file_in_memory) or die "Oops - $!\n";
close $fh;
}

__END__


It works fine for the first pass. However, subsequent passes emit warnings:

Pass #1
Pass #2
Use of uninitialized value in open at /perl/blah line 7.
Pass #3
Use of uninitialized value in open at /perl/blah line 7.

(line 7 is the "open" statement). Sure enough, if I make this change to "initialize" the scalar:

my $file_in_memory = '';

then I have no problems (except I bust the second rule of chapter 4 in Dr. Damian's _PBP_ - yikes).

Although the problem is easy enough to work around, I wonder why it behaves this way (which I don't see documented). The really strange thing (to me) is that it doesn't complain on the first pass. Any ideas?

Thx!

--
David Filmer (http://DavidFilmer.com)
.



Relevant Pages

  • Way to free memory as I input lines from a file?
    ... >memory then enter a loop where I input each line one by ... >I don't totally understand what the Filehandle & Freefile ... >be quicker to use (Open openfile For Binary Access Read ... >Below is a very cut down version of the loop I'm running, ...
    (microsoft.public.excel.programming)
  • Re: simple perl script on Windows
    ... Rather than getting the output of `dir`, just loop through the ... so it *ends* with a whitespace character - the ... print $FILE2 $line; ... filehandle, which it can't do, so the loop never executes. ...
    (perl.beginners)
  • Way to free memory as I input lines from a file?
    ... memory then enter a loop where I input each line one by ... I don't totally understand what the Filehandle & Freefile ... be quicker to use (Open openfile For Binary Access Read ... Below is a very cut down version of the loop I'm running, ...
    (microsoft.public.excel.programming)
  • Re: text wrap help...
    ... The "problem" is that you are reading the file with a whileloop. ... To maintain "good" practice and process the file with a whileloop, ... filehandle for DATA and print to your filehandle instead of STDOUT): ... 231146-76811 S.S. TAG-REF DESIG LABEL KIT ...
    (perl.beginners)
  • Re: Extarcting And Storing a String
    ... Digger wrote: ... will handle the file-opening for you. ... use openand a different while loop that uses the open's filehandle. ...
    (comp.lang.perl.misc)