- Perl ›
- File input/output ›
- here
Understand the concept of file handles
The concept of file handles in Perl is confusing, so I'll explain it here.
File handles are conceptual rather than real
When we talk about file handles in Perl, we mean multiple entities that Perl recognizes as file handles. There is no such thing as a file handle.
What Perl recognizes as a filehandle
- Symbol (FH)
- Type glob(* FH)
- Reference to typeglobs (\ * FH)
- IO::Handle class object
- An object of a class that inherits the IO::Handle object (such as IO::File)
Perl recognizes the above five as file handles. following statement are all valid.
# 1. Symbol FH open(FH, "<", $file) or die "$!"; # 2. Type glob * FH open(* FH, "<", $file) or die "$!"; # 3. Reference to typeglobs\* FH my $fh =\* FH; open($fh, "<", $file) or die "$!"; # 4. IO::Handle object use IO::Handle; my $fh = IO::Handle->new; open($fh, "<", $file) or die "$!"; # 5. IO::File object (inheriting IO::Handle) use IO::File; my $fh = IO::File->new; open($fh, "<", $file) or die "$!";
How to write a modern file open
How to write a modern file open
open(my $fh, "<", $file) or die "Can't open file $file:$!";
is.
When an undefined a scalar variable is passed as the first argument to the open function, a reference to the anonymous glob is automatically generated. With the same description as "3. Reference to typeglob(\ * FH)", only the part of my $fh =\* FH; is automatically performed. (This is a modern implementation of Perl, which may in the future automatically generate objects to IO::Handle.)