Perl中文件句柄引用的不同字符串表示形式

时间:2015-02-04 11:37:16

标签: perl

我从Intermediate Perl进行了练习8.2。它看起来像这样:

#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use autodie;

my %fhs;    # filehandles

while (<>) {
    unless (/^\s*(\S[^:]+):/) {
        warn "ignoring line with missing name: $_";
        next;
    }   
    my $castaway = lc $1; 

    unless ( $fhs{$castaway} ) { 
        my $fh = IO::File->new( $castaway . '.info', 'w' );
        #open my $fh, '>', "$castaway.info";
        $fhs{$castaway} = $fh;
    }   

    print { $fhs{$castaway} } $_; 
}   

use Data::Dumper;
print Dumper \%fhs;

(您可以从download page下载样本数据以运行程序 - 请参阅第8章。)

我尝试通过以下两种方式之一获取文件句柄:

my $fh = IO::File->new( $castaway . '.info', 'w' );
open my $fh, '>', "$castaway.info";

我猜它们是等价的但是当我转储%fhs哈希内容时,我会得到不同的结果。他们为什么不同?这是什么意思?感谢。

1 个答案:

答案 0 :(得分:2)

IO::File是文件句柄的面向对象接口。在内部,它做了同样的事情,但IO::File模块有一堆内置的方法来与你的文件句柄进行交互。

如果您查看了文档:http://perldoc.perl.org/IO/File.html

您会看到这一点 - 当您使用new时,结果是IO::File对象的实例,您可以通过->调用其中的方法。

E.g。

$fh -> close();

这与内置的perl不同close,尽管它的功能基本相同。

在幕后,在IO::File模块中,您可能会发现一个“真正的”文件句柄,但不需要使用perl运算符来进行自动清除,缓冲,行结尾等。

如果你看一下http://perldoc.perl.org/perlvar.htmlyou,我会看到一堆改变文件行为的全局变量:

  

$ |   如果设置为非零,则在当前所选输出通道上的每次写入或打印后立即强制刷新。

     

$ /   输入记录分隔符,默认为换行符。这会影响Perl关于“线”的概念。

等。 IO::File将这些隐藏在OO层之后。

http://perldoc.perl.org/perlvar.html#Variables-related-to-filehandles