The legacy bareword filehandle looks in global scope, is it parsed as package variable? Why isn't it prepended with punctuation sign ( $
)?
open FILE, 'file.txt';
If you look at perldoc -f ref
you will see that there are more data types than there are identifying sigils. The only defined ones are
$
- SCALAR @
- ARRAY %
- HASH &
- CODE the rest are identified by context.
If you write
package Pack;
open FH, '<', 'file';
then FH
appears in the Pack
symbol table as the IO variable Pack::FH
. It isn't preceded by a dollar $
because it is an IO variable, not a SCALAR . Without a preceding package
statement, it will be placed in the default main
namespace. So with your example
open FILE, 'file.txt'
you can then read from the FILE
handle using the fully-qualified main::FILE
like this
while (<main::FILE>) {
:
:
}
Used to be a convention in Perl - filehandles were all uppercase, and globally scoped.
This started with STDIN
(and the other standard file streams) and so you could do:
while ( <STDIN> ) {
print;
}
Perl's open command supports a 'legacy' mode of opening, which is:
open ( FILEHANDLE, ">filename.txt" );
It's not recommended to use this any more, but it can't be removed without breaking legacy code.
Instead you should:
open ( my $filehandle, ">", 'filename.txt' ) or die $!;
print {$filehandle} "Some Text\n";
This has two advantages:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.