Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't a filehandle need a sigil in Perl?

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?

like image 383
Ltf4an Avatar asked Dec 23 '22 23:12

Ltf4an


2 Answers

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.

like image 54
ysth Avatar answered Dec 27 '22 12:12

ysth


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.

like image 24
ikegami Avatar answered Dec 27 '22 11:12

ikegami