gpt4 book ai didi

perl - 有没有办法在 perl 中本地更改输入记录分隔符?

转载 作者:行者123 更新时间:2023-12-05 00:55:43 24 4
gpt4 key购买 nike

通过 my $x 将变量 $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";

关于perl - 有没有办法在 perl 中本地更改输入记录分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63623906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com