in reply to opening a file destroys nulling entries in a list?!?!
I'm not surprised you are confused:) I get the same behaviour with AS 5.8.
This isn't a bug, and what's more it is a doosy. I'm amazed I didn't recognise this as the normal behaviour of while. this hasn't shown up earlier. Actually I did, after trying to sleep for about 2 hours later. D'oh. It's the heat.
The problem lies with the while statement. Somehow, the aliasing of the input to $_ is getting mixd up with the first element of @_. This can be seen by printing the contents of the array just before the while and again inside it. Inside the loop, the first element of the array has been overwritten by the input from the diamond operator. At the end of the while loop, this then gets set to null. The original contents have been blown away!!
#!perl -sw use strict; $^W=0; my @instances = ('a', 'b', 'c'); sub screwed { my ($in) = @_; open(IN, '<', $in); print "before while: @instances\n"; # while(local $_ = <IN>) { while(<IN>) { chomp; print "after while: @instances\n"; print "file $in contains $_\n"; } close(IN); } print "before $_\n" for @instances; screwed $_ for @instances; print "after $_\n" for @instances; __END__ P:\test>test before a before b before c before while: a b c after while: a1 b c file a contains a1 after while: a2 b c file a contains a2 before while: b c after while: b1 c file b contains b1 after while: b2 c file b contains b2 before while: c after while: c1 file c contains c1 after while: c2 file c contains c2 after while: c3 file c contains c3 after after after
A work around is to explicitly localise $_ in the while as shown commented out above.
I'll raise a perlbug against this.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: opening a file destroys nulling entries in a list?!?!
by chromatic (Archbishop) on Aug 07, 2003 at 03:32 UTC | |
Re: Re: opening a file destroys nulling entries in a list?!?!
by matpalm (Initiate) on Aug 07, 2003 at 03:38 UTC | |
Re: Re: opening a file destroys nulling entries in a list?!?!
by IlyaM (Parson) on Aug 07, 2003 at 07:15 UTC |