gone2015 has asked for the wisdom of the Perl Monks concerning the following question:
UPDATE: I answered my own question here. And, the moral of the story is: those that live by $_ will die by $_ -- or, at least, are in danger of quite a nasty cut, requiring stitches and everything.
I was footling around looking at IO layers. So I set up some strings containing various test patterns, and used open FH, '<', \$foo to read each one -- so I could see what happened to each under different conditions.
The code below illustrates the general shape of what I was doing.
The interesting thing is that when I run this (v5.10.0) I get:
Fits: 5, 6, 7 Read: 'Fit I' Read: 'Fit II' Read: 'Fit III' Fits: 5, 6, 7 Read: 'Fit I' Read: 'Fit II' Read: 'Fit III' Fits: undef, undef, undef...so, somehow or other the entries in the array @fits have been set undef during the second foreach. Uh ?
The only difference between the first and second foreach is the use (or not) of a named variable. This is a serious surprise to me ! (I tried: our and my work the same way.)
Using the string as a "file" is obviously material. I haven't spotted any indication that this "eats" the string being "input". But, even if it does, my working model for Perl's parameter passing is that the my ($what) = @_ makes a copy of $_[0] (not another alias for whatever $_[0] is an alias for)...
So who mangled the entries in @fits, and was it with the lead pipe or the rope ?
Colour me curious -- any colour you like.
UPDATE: sorry ! The penny just dropped. It's a side effect of the file reading setting $_ to undef... and $_ is global, of course. Silly me. I'll get my coat.
use strict; use warnings; my $file_a = "Fit I" ; my $file_b = "Fit II" ; my $file_c = "Fit III" ; my @fits = ($file_a, $file_b, $file_c) ; show_fits() ; foreach my $f (@fits) { suck_this($f) ; } ; show_fits() ; foreach (@fits) { suck_this($_) ; } ; show_fits() ; sub show_fits { print "Fits: ", join(', ', map { defined($_) ? length($_) : 'undef' } @fits), "\n" ; } ; sub suck_this { my ($what) = @_ ; open my $FH, '<', \$what ; print " Read:" ; while (<$FH>) { s/\r/\\r/g ; s/\n/\\n/g ; print " '$_'" ; } ; print "\n" ; } ;
|
|---|