Nice bear trap with $FOO file handle and $_

D

Dave Saville

Just fell into a nice bear trap.

open FOO, '>', $bar or die "$!";
while ( <some file> )
{
print FOO;
}

I was changing my scripts to using $HANDLE - AIUI this is s "Good
Thing(TM)" although I am not sure why :)

So the above print turned into "print $FOO;" - which of course does
not default to printing $_. It prints a GLOB to STDOUT.
 
R

Rainer Weikusat

Ben Morrow said:
Quoth "Dave Saville" <[email protected]>:
[...]
I was changing my scripts to using $HANDLE - AIUI this is s "Good
Thing(TM)" although I am not sure why :)

Suppose you are working on a large program. Also suppose that in your
program you have a function foo

sub foo {
...
open FOO, ">", $bar or...;
bar();
print FOO;
}

and a function bar

sub bar {
...
open FOO, ">", $somewhere_else or...;
my @lines = <FOO>;
close FOO;
}

foo will not work as expected, since bar will reopen and then close the
same filehandle as foo is using, but this is not at all obvious from
looking at foo itself.

That's sort-of a disingenious example because just using

sub foo
{
local *FOO;

and

sub bar
{
local *FOO;

the old-style way for creating local file handles, would work fine
here. The downside of this is that using local changes the environment
for all subroutines called from the subroutine containing the
local: The newly created glob is implicitly accessible from all
subroutines called from either foo or bar (and to subroutines called
from these subroutines and so on) and it may even cause them to access
a different filehandle then the one they were supposed to
access. Because of this, local should be avoided except when this
particular phenomenon is actually the desired behaviour.
 
D

Dave Saville

Suppose you are working on a large program. Also suppose that in your
program you have a function foo

sub foo {
...
open FOO, ">", $bar or...;
bar();
print FOO;
}

and a function bar

sub bar {
...
open FOO, ">", $somewhere_else or...;
my @lines = <FOO>;
close FOO;
}

foo will not work as expected, since bar will reopen and then close the
same filehandle as foo is using, but this is not at all obvious from
looking at foo itself. If they are in different files, or indeed if bar
is in some module you are using which you didn't write yourself, it may
take a while for you to work out where the problem is.

Thanks for the explanation Ben. I *knew* there was a good reason :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top