4

In Perl, filehandle is a data type, and I'd expect a variable of such type has some kind of sigil prefix. However, the following code (2nd open) shows that it's not the case

open my $fileHandle, '>', "out.txt";
open FH, '>', "out2.txt";

I found the 2nd form confusing/inconsistent. What is the reason for allowing the 2nd form?

Ltf4an
  • 787
  • 5
  • 18

2 Answers2

6

The second form is allowed because it is the original one. You used to only be able to refer to filehandles by the name of the glob that contained them. Now filehandles can be the name of a glob or a reference to a glob wrapped around a filehandle object or a reference to a filehandle object. The latter two can be stored in a scalar (and so can be lexically scoped).

You should avoid using globs as filehandles in new code.

ysth
  • 96,171
  • 6
  • 121
  • 214
  • ysth: How is "a reference to a glob wrapped around a filehandle object" different from "a reference to a filehandle object"? Would you please give examples of the two cases? – Ltf4an Nov 27 '16 at 18:21
  • @Ltf4an you have to go out of your way to get the latter (e.g. `*SOMEGLOB{IO}` or `Symbol::geniosym()`); I mentioned it only for completeness. There usually isn't any reason to, unless you are playing around with the symbol table. – ysth Nov 27 '16 at 18:35
4

Generally speaking, you do need a sigil when referencing a glob.

my $fh = STDOUT;    # XXX Short for: my $fh = "STDOUT";
my $fh = *STDOUT;   # ok

However, functions that expect a glob (e.g. open, print, readline aka <>, etc) make it optional.

print STDOUT "foo\n";   # Short for: print *STDOUT "foo\n";

You can approximate this with the * prototype.

sub foo { }
sub bar(*) { }

foo(STDOUT);   # XXX Fails when using "use strict;"
bar(STDOUT);   # ok

What is the reason for allowing the 2nd form?

The second form (which uses a global symbol) predates the support for open(my $fh, ...) introduced in 5.6. In fact, it predates the existence of lexical (my) variables. Since one should avoid global variables whenever possible, the open(FH, ...) is discouraged.

ikegami
  • 367,544
  • 15
  • 269
  • 518