Daanish
Daanish

Reputation: 1091

Are filehandles in perl global?

#!/usr/local/bin/perl
sub trial
{
    open (LOGFILE, 'C:\Users\out.txt');
    trial();
}
trial();

Please ignore that it will go into an infinite loop.

Will the filehandle LOGFILE be local or private to the method? If no, how can I make it private/local? I'm aware of my . But I don't know how to use it on File Handles.

Upvotes: 4

Views: 3870

Answers (2)

simbabque
simbabque

Reputation: 54323

Those filehandles are global because they are typeglobs. This can lead to very bad surprises sometimes, because you might by accident overwrite such a filehandle that was defined inside of some module you are using.

If you want lexical filehandles, define them with my like this:

open my $fh, '<', 'C:\Users\out.txt';

See also:

Upvotes: 10

Quentin
Quentin

Reputation: 943537

Lexical file handles are just standard my scalars. See the examples in the perldoc for open.

open (my $logfile, 'C:\Users\out.txt');

In general, the three argument form of open is preferred too:

open (my $logfile, '<', 'C:\Users\out.txt');

Upvotes: 4

Related Questions