Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are filehandles in perl global?

Tags:

perl

#!/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.

like image 811
Daanish Avatar asked Dec 09 '22 20:12

Daanish


1 Answers

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:

  • Which one is good practice, a lexical filehandle or a typeglob?
  • brian d foy on 'Why we teach bareword filehandles' in Learning Perl
like image 63
simbabque Avatar answered Jan 05 '23 22:01

simbabque