如何解决有没有办法在Perl中本地更改输入记录分隔符?
通过$x
将变量my $x
的范围限制为特定的代码块或子例程,从而避免了由“全局变量”引起的混乱的编码器。
但是,当涉及到输入记录分隔符$/
时,显然不能限制其范围。
我对吗?
因此,如果我忘记在循环结束时或在子例程内部重置输入记录分隔符,则调用该子例程的下面代码可能会产生意外的结果。 以下示例对此进行了演示。
#!/usr/bin/perl
use strict; use warnings;
my $count_records; my $infile = $ARGV[0]; my $HANDLEinfile;
open $HANDLEinfile,'<',$infile or die "cannot open $infile for reading";
$count_records = 0;
while(<$HANDLEinfile>)
{
$count_records++;
print "$count_records:\n";
print;
}
close $HANDLEinfile;
look_through_other_file();
print "\nNOW,after invoking look_through_other_file:\n";
open $HANDLEinfile,$infile or die "cannot open $infile for reading";
$count_records = 0;
while(<$HANDLEinfile>)
{
$count_records++;
print "$count_records:\n";
print;
}
close $HANDLEinfile;
sub look_through_other_file
{
$/ = undef;
# here,look through some other file with a while loop
return;
}
这是输入文件上的行为:
> z.pl junk
1:
All work
2:
and
3:
no play
4:
makes Jack a dull boy.
NOW,after invoking look_through_other_file:
1:
All work
and
no play
makes Jack a dull boy.
>
请注意,如果尝试更改为
my $/ = undef;
在子例程中,这会生成错误。
顺便说一句,在stackoverflow标签中,为什么没有用于“输入记录分隔符”的标签?
解决方法
my $/ = undef;
问题的答案是将其更改为local $/ = undef;
。然后修改后的代码如下。
#!/usr/bin/perl
use strict; use warnings;
my $count_records; my $infile = $ARGV[0]; my $HANDLEinfile;
open $HANDLEinfile,'<',$infile or die "cannot open $infile for reading";
$count_records = 0;
while(<$HANDLEinfile>)
{
$count_records++;
print "$count_records:\n";
print;
}
close $HANDLEinfile;
look_through_other_file();
print "\nNOW,after invoking look_through_other_file:\n";
open $HANDLEinfile,$infile or die "cannot open $infile for reading";
$count_records = 0;
while(<$HANDLEinfile>)
{
$count_records++;
print "$count_records:\n";
print;
}
close $HANDLEinfile;
sub look_through_other_file
{
local $/ = undef;
# here,look through some other file with a while loop
return;
}
然后,无需手动将输入记录分隔符返回到另一个值或默认值$/ = "\n";
。
您可以使用local
来临时更新全局变量的值,包括$/
。
sub look_through_other_file {
local $/ = undef;
# here,look through some other file with a while loop
return;
}
只要$/
子例程在调用堆栈中,将使用未定义的look_through_other_file
。
您可能会在这种常见用法中遇到这种构造,即将文件的整个内容包含到变量中,而无需更改程序其余部分的$/
的值:
open my $fh,"<","/some/file";
my $o = do { local $/; <$fh> };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。