gpt4 book ai didi

perl 正则表达式警告 :\1 better written as $1 at (eval 1) line 1

转载 作者:行者123 更新时间:2023-12-01 10:10:26 26 4
gpt4 key购买 nike

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";

运行它会给我正确的结果:
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

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

最佳答案

\1是一个正则表达式模式,意思是“匹配第一组捕获括号捕获的内容”。在替换表达式中使用它绝对没有意义。要获取第一组捕获括号捕获的字符串,请使用 $1 .

$line =~ s/pwd(\s*)=.*/pwd\1= $newPasswd/

应该
$line =~ s/pwd(\s*)=.*/pwd$1= $newPasswd/

所以
'pwd(\\s*)=.*'      => 'pwd\\1= $newPasswd',
'password(\\s*)=.*' => 'password\\1= $newPasswd',

应该
'pwd(\\s*)=.*'      => 'pwd$1= $newPasswd',
'password(\\s*)=.*' => 'password$1= $newPasswd',

或者更好
qr/((?:pwd|password)\s*=).*/ => '$1= $newPasswd',

关于perl 正则表达式警告 :\1 better written as $1 at (eval 1) line 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5747427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com