我一定遗漏了一些关于变量赋值或字符串比较的内容。我有一个正在处理制表符分隔文件的脚本。除非一行中的一个特定值是“P”,否则我想跳到下一行。代码如下:
1 print "Processing inst_report file...\n";
2 foreach(@inst_report_file){
3 @line=split(/\t/);
4 ($line[13] ne "P") && next;
5 $inst_report{$line[1]}++;
6 }
出于某种原因,脚本永远不会到达第 5 行,即使其中有明显带有“P”的行。
调试时间到了!
# Continuing to the breakpoint.
DB<13> c
main::(count.pl:27): ($line[13] ne "P") && next;
# Proving that this particular array element is indeed "P" with no leading or trailing characters.
DB<13> p "--$line[13]--\n";
--P--
# Proving that I'm not crazy and the Perl string comparison operator really works.
DB<14> p ("P" eq "P");
1
# Now since we've shown that $line[13] eq P, let's run that Boolean again.
DB<15> p ($line[13] eq "P")
# (Blank means FALSE) Whaaaat?
# Let's manually set $line[13]
DB<16> $line[13]="P"
# Now let's try that comparison again...
DB<17> p ($line[13] eq "P")
1
DB<18>
# Now it works. Why?
我可以通过预过滤输入文件来解决这个问题,但让我困扰的是为什么这不起作用。我是否遗漏了一些明显的东西?
---洛伦---
最佳答案
找出你的字符串真正使用的是什么:
use Data::Dumper;
local $Data::Dumper::Useqq = 1;
print(Dumper($line[13]));
<小时/>
[经进一步审查,以下猜测很可能是错误的。 ]
我怀疑您有一个尾随换行符,在这种情况下您需要 chomp
.
您还可以有尾随空格。 s/\s+\z//
将删除尾随空格和尾随换行符。
关于string - 我对 Perl 字符串比较运算符感到疯狂吗?包含调试日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7277813/