Perl match only returning “1”. Booleans? Why?

后端 未结 6 893
星月不相逢
星月不相逢 2021-01-18 13:18

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
[         


        
6条回答
  •  盖世英雄少女心
    2021-01-18 13:35

    The =~ perl operator takes a string (left operand) and a regular expression (right operand) and matches the string against the RE, returning a boolean value (true or false) depending on whether the re matches.

    Now perl doesn't really have a boolean type -- instead every value (of any type) is treated as either 'true' or 'false' when in a boolean context -- most things are 'true', but the empty string and the special 'undef' value for undefined things are false. So when returning a boolean, it generall uses '1' for true and '' (empty string) for false.

    Now as to your last question, where trying to print $1 prints nothing. Whenever you match a regular expression, perl sets $1, $2 ... to the values of parenthesized subexpressions withing the RE. In your example however, there are NO parenthesized sub expressions, so $1 is always empty. If you change it to

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

    You'll get something more like what you expect (Defect if it matches and nothing if it doesn't).

    The most common idiom for regexp matching I generally see is something like:

    if ($string =~ /regexp with () subexpressions/) {
        ... code that uses $1 etc for the subexpressions matched
    } else {
        ... code for when the expression doesn't match at all
    }
    

提交回复
热议问题