我试图找出正确的 PBP 批准的方式来一次处理多行字符串。许多 Perl 编码人员建议将多行字符串视为文件句柄,除非您在脚本中使用“use strict”,否则它可以正常工作。然后你会从编译器那里得到一个警告,说在使用严格引用时不能将字符串用作符号。
这是该问题的一个简单的工作示例:
#use strict;
use warnings;
my $return = `dir`;
my $ResultsHandle = "";
my $matchLines = "";
my $resultLine = "";
open $ResultsHandle, '<', \$return;
while (defined ($resultLine = <$ResultsHandle>)) {
if ($resultLine =~ m/joe/) {
$matchLines = $matchLines . "\t" . $resultLine;
}
}
close($ResultsHandle);
print "Original string: \n$return\n";
print "Found these matching lines: \n$matchLines\n";
请注意,“use strict”行已被注释掉。当我在不使用严格的情况下运行此脚本时,我得到了我想要的和期望的:
Original string:
Volume in drive D has no label.
Volume Serial Number is 50D3-54A6
Directory of D:\Documents and Settings\username\My Documents\Eclipse\myTestProject
09/18/2009 11:38 AM <DIR> .
09/18/2009 11:38 AM <DIR> ..
09/18/2009 11:36 AM 394 .project
09/18/2009 11:37 AM 0 joe.txt
09/18/2009 11:37 AM 0 joey.txt
09/18/2009 11:38 AM 0 kurt.txt
09/18/2009 11:43 AM 497 main.pl
09/18/2009 11:38 AM 0 shane.txt
6 File(s) 891 bytes
2 Dir(s) 6,656,188,416 bytes free
Found these matching lines:
09/18/2009 11:37 AM 0 joe.txt
09/18/2009 11:37 AM 0 joey.txt
不过,这就是问题所在。当我取消注释“use strict”行时,我从 Perl 收到以下警告或错误:
Can't use string ("") as a symbol ref while "strict refs" in use at D:/Documents and Settings/username/My Documents/Eclipse/myTestProject/main.pl line 8.
第 8 行是“打开 $ResultsHandle, '<', \$return;” 顺便说一句,线。因此,既然 Perl 最佳实践要求我使用严格,那么 PBP 如何期望我一次处理多行字符串?SO社区有什么建议吗?
谢谢!