Warning on uninitailized variable despite undef checking

Today I seem to be very stupid, or I have a very strange problem. Please consider the following code:

#!/usr/bin/perl

use strict;
use warnings;
use warnings::unused;
use warnings FATAL => 'uninitialized';

my ($String, $Pattern);

$Pattern = "pattern";
$String = "pattern\n";

if (($String =~ m/^([^\ ]+).*$/s) &&
    defined($1) &&
    ($1 =~ m/^.*$Pattern$/s)) {

  print $1."\n";
}

This code issues the following warning (and then stops due use warnings FATAL => 'uninitialized';):

Use of uninitialized value $1 in concatenation (.) or string at [...]

I really do not understand this because I am testing if it is $1defined (initialized) before using it. The culprit is apparently the last line of the condition (i.e. ($1 =~ m/^.*$Pattern$/s)). If I leave this, the warning will disappear.

But why? In my opinion, this line should just test $1, but not change its value ( $Patternand the rest of this RegEx does not contain parentheses, so $1you should not reassign a possible match).

... , , Perl $1 , RegEx , RegEx . . ?

+4
3

:

if (($String =~ m/^([^\ ]+).*$/s) && # If matching, this will set $1
    defined($1) &&                   # Here $1 is still defined
    ($1 =~ m/^.*$Pattern$/s)         # If matching, will reset all $1, .. vars
) {

, , , reset ( , ).

, , $1 . , .

if ($String =~ m/^([^\ ]+).*$/s and defined $1) {
    my $match = $1;
    if ($match =~ m/^.*$Pattern$/s) { ... }
}

, defined $1, , $1 . .

perldoc perlvar:

$<digits> ($1, $2, ...)
        Contains the subpattern from the corresponding set of capturing
        parentheses from the last successful pattern match [...]
+8

perldoc perlvar:

, , .

, if $1 undef.

:

my ($match) = ($String =~ m/^([^\ ]+).*$/s);
if (defined $match && $match =~ m/^.*$Pattern$/s) {
    print $match."\n";
}
+9

If you do not know what a complex instruction does, divide it into parts.

if( $String =~ m/^([^\ ]+).*$/s ){
    if( defined($1) ){
        if( $1 =~ m/^.*$Pattern$/s ){
0
source

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


All Articles