文件“/serrs/env.txt”的内容是:
abc
def
ghi jkl mno
good is the conet
Run Code Online (Sandbox Code Playgroud)
代码片段是:
use strict;
use warnings;
my $ModeRefFile;
open(FH2, '<', "/home/vivi/ee/ppp.pl") or die $!;
local $/ = undef;
$ModeRefFile = <FH2>;
close(FH2);
open(FH3, '<', "/serrs/env.txt") or die $!;
while (<FH3>) {
chomp ($_);
print "$_ is the line which is being read\n";
}
close(FH3);
Run Code Online (Sandbox Code Playgroud)
输出:
abc
def
ghi jkl mno
good is the conet is the line which is being read
Run Code Online (Sandbox Code Playgroud)
我想要什么(预期):
abc is the line which is being read
def is the line which is being read
ghi jkl mno is the line which is being read
good is the conet is the line which is being read
Run Code Online (Sandbox Code Playgroud)
为什么第二个 open ( open(FH3, '<', "/serrs/env.txt") 中的 $_ 存储文件的全部内容,即使输出记录运算符在第一个 open ( open(FH2, '<', "/home/vivi/ee/ppp.pl")) 中更改,并且也使用“local”。根据我的理解,第二个 open ( open(FH3, '<', "/serrs/env.txt") 中的 $_ 应包含每一行。我怎样才能实现它?
local $/或local $/ = undef、 或$/ = undef都是执行同一操作的不同方法,即禁用记录输入分隔符。如果您local在文件的顶部块(或同一块)中使用,则它没有任何效果,但将在整个文件中全局使用。这local也是覆盖已存在变量的一种方法,意思是“这是变量的本地版本”。
惯用的使用方法local $/是这样的:
my $filecontent = do {
open my $fh, '<', "foo.bar" or die $!;
local $/; # local version of $/, now undef
<$fh>; # return the whole file in one string
};
Run Code Online (Sandbox Code Playgroud)
这样,local $/就可以在需要的地方保留词法作用域,并且不会影响代码的其余部分。
此外,通过这种方式,您的文件句柄具有词法作用域,并在块结束时关闭。
代码的另一个有趣的副作用是chomp现在不会删除任何内容,因为它是由$/.
的文档是local()这样说的:
局部变量将列出的变量修改为封闭块、文件或 eval 的局部变量。
这里重要的是“封闭块”。您的调用周围没有封闭块local(),因此它对程序的其余部分有效 - 包括当您正在处理时FH3。
代替:
local $/ = undef;
$ModeRefFile = <FH2>;
Run Code Online (Sandbox Code Playgroud)
尝试这个:
$ModeRefFile = do { local $/; <FH2> };
Run Code Online (Sandbox Code Playgroud)
这样,local()只有在代码块内有效。