有没有办法在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> };

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...