Messing with bareword filehandles

Matts on 2005-08-02T15:29:55

We were having a conversation on the KW.pm IRC channel (and our network is down at work so I can't really do any work work) about bareword filehandles this morning.

We started off talking about how bwfhs are bad compared to lexical filehandles (at least for most use cases). Then I noted that the one advantage is that if you use UPPERCASE bwfhs they are easy to see in code.

So we got talking about lower case bwfhs, and how horrible they are because they look like functions. So what happens if you use a lower-case bwfh that has the same name as a builtin function?

open lc, ">/tmp/foo"; print lc "Yadda Yadda Yadda\n";
That, as most long-time perlers would expect, prints "yadda yadda yadda\n" to the currently selected filehandle.

But there's a consequence. It does NOT open "/tmp/foo" into the bwfh "lc" - it opens it onto lc($_). Which is the empty string (lower cased).

So the next question is can you print to the bwfh represented by the empty string?

My first try was this:
open lc, ">/tmp/foo"; ""->print("Yikes\n");


That works, if you have IO::Handle loaded. But it's a bit too clear what you're doing.

Second try:
open lc, ">/tmp/foo"; select ""; print "Yikes\n";


That works. It's still a little clear. Lets select something else.
open lc, ">/tmp/foo"; select uc; print "Yikes\n";


Neat huh?

Yeah I hear you - back to work Sergeant...


Evil!

Aristotle on 2005-08-04T00:16:12

And I like it. :-)