perl正则表达式警告:\ 1最好在(eval 1)第1行写为$ 1

Joh*_*ohn 3 syntax perl warnings

use strict;
use warnings;

my $newPasswd = 'abc123';
my @lines = ( "pwd = abc", "pwd=abc", "password=def", "name= Mike" );

my %passwordMap = (
    'pwd(\\s*)=.*'      => 'pwd\\1= $newPasswd',
    'password(\\s*)=.*' => 'password\\1= $newPasswd',
);

print "@lines\n";

foreach my $line (@lines) {
    while ( my ( $key, $value ) = each(%passwordMap) ) {
        if ( $line =~ /$key/ ) {
            my $cmdStr = "\$line =~ s/$key/$value/";
            print "$cmdStr\n";
            eval($cmdStr);
            last;
        }
    }
}

print "@lines";
Run Code Online (Sandbox Code Playgroud)

运行它会给我正确的结果:

pwd = abc pwd=abc password=def name= Mike
$line =~ s/pwd(\s*)=.*/pwd\1= $newPasswd/
\1 better written as $1 at (eval 2) line 1 (#1)
$line =~ s/password(\s*)=.*/password\1= $newPasswd/
\1 better written as $1 at (eval 3) line 1 (#1)
pwd = abc123 pwd=abc password= abc123 name= Mike
Run Code Online (Sandbox Code Playgroud)

我不想看到警告,试图使用$ 1而不是\ 1,但它不起作用.我该怎么办?非常感谢.

ike*_*ami 6

\1是一个正则表达式模式,意思是"匹配第一组捕获parens捕获的内容." 在替换表达式中使用它是完全没有意义的.要获取第一组捕获parens捕获的字符串,请使用$1.

$line =~ s/pwd(\s*)=.*/pwd\1= $newPasswd/
Run Code Online (Sandbox Code Playgroud)

应该

$line =~ s/pwd(\s*)=.*/pwd$1= $newPasswd/
Run Code Online (Sandbox Code Playgroud)

所以

'pwd(\\s*)=.*'      => 'pwd\\1= $newPasswd',
'password(\\s*)=.*' => 'password\\1= $newPasswd',
Run Code Online (Sandbox Code Playgroud)

应该

'pwd(\\s*)=.*'      => 'pwd$1= $newPasswd',
'password(\\s*)=.*' => 'password$1= $newPasswd',
Run Code Online (Sandbox Code Playgroud)

还是更好

qr/((?:pwd|password)\s*=).*/ => '$1= $newPasswd',
Run Code Online (Sandbox Code Playgroud)