Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl match only returning "1". Booleans? Why?

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.

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;

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

Alternatively:

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

prints absolutely nothing.

$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.

like image 532
ManAnimal Avatar asked Oct 21 '11 21:10

ManAnimal


People also ask

Which modifier interpolates variables only once in the pattern matching?

If you want such a pattern to be compiled once and only once, use the /o modifier. This prevents expensive run-time recompilations; it's useful when the value you are interpolating won't change during execution.

How do I get the matched pattern in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.

What is =~ in Perl?

The Binding Operator, =~ Matching against $_ is merely the default; the binding operator ( =~ ) tells Perl to match the pattern on the right against the string on the left, instead of matching against $_ .

What is in Perl regex?

Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“.


2 Answers

You need to use capturing parentheses to actually capture:

if ($record =~ /(Defect)/ ) {
    print "$1\n";
}
like image 54
Sinan Ünür Avatar answered Nov 19 '22 16:11

Sinan Ünür


I think what you really want is to wrap the regex in parentheses:

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

In list context, the groups are returned, not the match itself. And your original code has no groups.

like image 40
sidyll Avatar answered Nov 19 '22 17:11

sidyll