How to ignore any empty values โ€‹โ€‹in perl grep?

I use the following to count the number of occurrences of a template in a file:

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

But sometimes it prints another value than the actual value. I checked, and this is because the last @lines element is NULL, and this is also considered.

How can there sometimes be the last element of a grep result? Also, how to solve this problem?

+6
source share
4 answers

It really depends a lot on your template, but one thing you can do is join a few matches, the first of which will disqualify any line containing only a space (or nothing). In this example, any line that is either empty, only a new line, or any number of spaces will be rejected.

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

Keep in mind that if the contents of the $ include test include special regexp metacharacters, they must either be designed for their metacharacters or sterilized with quotemeta() .

My theories are that you may have a string ending in \ n that somehow matches your text regular expression, or your regular $ text expression contains metacharacters in it that affect matching if you don't know. In any case, the fragment I provided will at least lead to the rejection of โ€œempty linesโ€, where empty can mean completely empty (unlikely), the end of a new line, but otherwise empty (likely), or spaces containing (possible ) lines that will be empty when printing.

+6
source

A regular expression that matches an empty string will match undef . Perl will warn about this, but discards undef before '' before trying to match it, and at this point grep will rather happily push undef to its results. If you do not want to take an empty string (or anything that matches, as if it were an empty string), you need to rewrite your regular expression so that it does not match it.

+2
source

To see exactly what is in the lines, do:

 use Data::Dumper; $Data::Dumper::Useqq = 1; print Dumper \@lines; 
+2
source

Well, since more information about the contents of $text (regular expression) is not expected, I think I will discard some general information.

Consider the following example:

 use Data::Dumper; my @array = (' ', 1, 2, 'a', ''); print Dumper [ grep /\s*/, @array ]; 

We get:

 $VAR1 = [ ' ', 1, 2, 'a', '' ]; 

All values โ€‹โ€‹correspond. What for? Because they also match an empty string. To get what we want, we need \s or \s+ . (There will be no practical difference between them)

You may have such a problem.

0
source

Source: https://habr.com/ru/post/892365/


All Articles