如何忽略一个Perl的grep任何空值? [英] How to ignore any empty values in a perl grep?

查看:292
本文介绍了如何忽略一个Perl的grep任何空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的计算在文件中的模式的出现的次数:

I am using the following to count the number of occurrences of a pattern in a file:

my @lines = grep /$text/, <$fp>;
print ($#lines + 1);

但有时它打印比实际值一个。我查了一下,这是因为 @lines 的最后一个元素为null,并且也计算在内。

But sometimes it prints one more than the actual value. I checked and it is because the last element of @lines is null, and that is also counted.

grep的结果的最后一个元素怎么会空有时?此外,这怎么能问题得到解决?

How can the last element of the grep result be empty sometimes? Also, how can this issue be resolved?

推荐答案

这真的取决于你的模式很多,但是有一件事你可以做的是参加几场比赛中,第一个不合格只包含空格的任何行(或没有)。这个例子将拒绝任何行要么是空的,只有换行,空格或任意数量的唯一。

It really depends a lot on your pattern, but one thing you could do is join a couple of matches, the first one disqualifying any line that contains only space (or nothing). This example will reject any line that is either empty, newline only, or any amount of whitespace only.

my @lines = grep { not /^\s*$/ and /$test/ } <$fp>;

请记住,如果$测试的内容发生在包括正则表达式特殊的元字符他们要么必须针对他们的元字符的目的,或与消毒quotemeta()

Keep in mind that if the contents of $test happen to include regexp special metacharacters they either need to be intended for their metacharacter purposes, or sterilized with quotemeta().

我的理论是,你可能在\\ n这在某种程度上符合$文本的正则表达式终止一条线,或$文本的正则表达式中包含它元字符,表示正在影响比赛而你没有注意到。无论哪种方式,我公司提供的片段将至少力甩空行,其中空白可能意味着完全是空的(不太可能),换行终止,但在打印时出现空白,否则空(可能的),或含有空格(可能)线。

My theories are that you might have a line terminated in \n which is somehow matching your $text regexp, or your $text regexp contains metacharacters in it that are affecting the match without you being aware. Either way, the snippet I provided will at least force rejection of "blank lines", where blank could mean completely empty (unlikely), newline terminated but otherwise empty (probable), or whitespace containing (possible) lines that appear blank when printed.

这篇关于如何忽略一个Perl的grep任何空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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