Perl匹配仅返回"1".布尔值?为什么? [英] Perl match only returning "1". Booleans? Why?

查看:131
本文介绍了Perl匹配仅返回"1".布尔值?为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很明显,但我只是没有看到.

This has got to be obvious but I'm just not seeing it.

我有一个包含数千条记录的文档,如下所示:

I have a documents containing thousands of records just like below:

Row:1 DATA:
[0]37755442
[1]DDG00000010
[2]FALLS
[3]IMAGE
[4]Defect
[5]3
[6]CLOSED

我设法将每个记录分开,现在我试图解析每个字段.

I've managed to get each record separated and I'm now trying to parse out each field.

我正在尝试匹配编号的标头,以便提取出接在它们后面的数据,但是问题是,当它们成功时,我的匹配项只会返回"1",如果没有,则什么也不会返回.我尝试申请的任何比赛都在发生这种情况.

I'm trying to match the numbered headers so that I can pull out the data that succeeds them but the problem is that my matches are only returning me "1" when they succeed and nothing if they don't. This is happening for any match I try to apply.

例如,应用于每个记录中的一个简单单词:

For instance, applied to a simple word within each record:

my($foo) = $record=~ /Defect/;
print STDOUT $foo;

如果每个记录包含缺陷",则为每个记录打印出"1",如果包含其他内容则不打印任何记录.

prints out out a "1" for each record if it contains "Defect" and nothing if it contains something else.

或者:

$record =~ /Defect/;
print STDOUT $1;

绝对不打印任何内容.

$record =~ s/Defect/Blefect/

另一方面,将缺陷"替换为完美".

will replace "Defect" with "Blefect" perfectly fine on the other hand.

我真的很困惑为什么我的比赛收益如此之高. 任何帮助将不胜感激.

I'm really confused as to why the returns on my matches are so screwy. Any help would be much appreciated.

推荐答案

您需要使用捕获括号来实际捕获:

You need to use capturing parentheses to actually capture:

if ($record =~ /(Defect)/ ) {
    print "$1\n";
}

这篇关于Perl匹配仅返回"1".布尔值?为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆