Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: opening a file destroys nulling entries in a list?!?!

by cfreak (Chaplain)
on Aug 07, 2003 at 02:56 UTC ( #281712=note: print w/replies, xml ) Need Help??

in reply to opening a file destroys nulling entries in a list?!?!

$_ is a global variable. Your while is setting it to the last record of your filehandle and since your files end with a \n, $_ returns blank (I guess $_ gets set before the test is done to see if it has a value). Since this is Perl there is more than one way to get around this:

You can localize $_ in your sub like so:

sub screwed { my ($in) = @_; local $_; # basically a temporary $_ just for this sub open(IN, "<$in"); while(<IN>) { print "file $in contains $_"; } close(IN); }
Or you can set each line of the file to a variable in the while like so:
while(defined(my $foo = <IN>)) { print "file $in contains $foo"; }

Hope that helps

Lobster Aliens Are attacking the world!

Replies are listed 'Best First'.
Re: Re: opening a file destroys nulling entries in a list?!?!
by sgifford (Prior) on Aug 07, 2003 at 03:32 UTC
    To elaborate a bit (it took me some experimenting to realize why cfreak is right), inside a map the variable $_ is magic. While each entry in the list is evaluated, $_ is an alias to that entry. Assigning a new value to $_ changes the value of the current list entry. Because you're calling screwed from within map without localizing $_, it's being assigned to each successive line in the file, and then set to undef to indicate end-of-file. When screwed returns, $_ is still set to undef, so all entries in the list are changed to undef.

    You can verify this by changing screwed to:

    sub screwed { $_ = 'hi'; }
    in which case you'll get:
    before a
    before b
    after hi
    after hi
Re: Re: opening a file destroys nulling entries in a list?!?!
by bobn (Chaplain) on Aug 07, 2003 at 03:38 UTC

    How come while(<IN>){}, but not for (@x) {}? why is while (<IN>) so special?

    I love perl, but this scares the hell out of me.

    --Bob Niederman,

      Nevermend. I think I get it - someone else posted that while(<>){} is the same as while($_=<>){} - it does an assignment to $_ and that's what does the damage.

      Somehwere, I think I remember someone (Tom Christiansen, I think) saying to always localize $_ in subroutines. Now I know why.

      --Bob Niederman,

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://281712]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2016-10-26 04:20 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (333 votes). Check out past polls.