Perl变量之间的混淆

Gri*_*gor 2 perl

我有以下代码

my $content = $response->content;
$content =~ /username=([\s\S]+?)&/;
my $username = $1;
print $username; #Prints the text
Run Code Online (Sandbox Code Playgroud)

让我说我想再次这样做,但对于不同的文本

例如

$content =~ /rank=([\s\S]+?)&/;
my $rank = $1;
print $rank; #Prints the username text
Run Code Online (Sandbox Code Playgroud)

我必须将$ 1更改为其他内容吗?

Tud*_*tin 9

my $content = $response->content;
$content =~ /username=([\s\S]+?)&/;
my $username = $1;
print $username; #Prints the text

$content =~ /rank=([\s\S]+?)&/;

#if the above regex does not match, $1 remains set to the previous $1

my $rank = $1;
print $rank; #Prints the username text
Run Code Online (Sandbox Code Playgroud)

这将是更安全的东西:

if ($content =~ /rank=([\s\S]+?)&/){
    my $rank = $1;
}
Run Code Online (Sandbox Code Playgroud)

或者,更优雅:

my ($rank) = $content =~ /rank=([\s\S]+?)&/;
print "\n rank:$rank" if defined $rank; #Prints the username text
Run Code Online (Sandbox Code Playgroud)