Jac*_*lin 2 perl file-io parsing text-processing
将变量的范围限制$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;
}
Run Code Online (Sandbox Code Playgroud)
以下是它在输入文件上的行为:
> 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.
>
Run Code Online (Sandbox Code Playgroud)
请注意,如果尝试更改为
my $/ = undef;
Run Code Online (Sandbox Code Playgroud)
在子程序内部,这会产生错误。
顺便说一句,在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;
}
Run Code Online (Sandbox Code Playgroud)
这样就不需要$/ = "\n";手动将输入记录分隔符返回到另一个值,或者返回到默认值。