Perl 从字符串中捕获的数字总是 1

Perl captured digits from string are always 1

开始学习的路上perl...

我遇到了这种有趣的行为,似乎无法理解它。

my $username = "bandit0";
my $command = "";

sub next_command {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    print "$num\n";
    if ($num == 0){
        return "cat readme";
    }
    elsif ($num == 1){
        return "ls";
    }
}

sub next_level {
    my ($user) = @_;
    my $num = $user =~ /(\d+)/;
    $user =~ s/\d//g;
    $user = $user . $num++;
    return $user;
}

$command = next_command($username);
print $command . "\n";
$username = next_level($username);
$command = next_command($username);
print $command . "\n";

在 运行 这个小的 perl 程序之后,我希望是这样的:

0
cat readme
1
ls

但是我得到了这样的东西...

1
ls
1
ls

我不明白为什么,一开始字符串 bandit0 $num 会是 1 而不是 0

您可以尝试一下,看看是否有效。如果有帮助,我会解释一切。我现在无法自己测试。

use strict;   # always use strict
use warnings; # always use warnings

my $username = "bandit0"; #try bandit1 to ensure it prints 1 and ls instead
my $command = "";

sub next_command {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)/;
    print "$num\n";
    if ($num == 0){
       return "cat readme";
    }

    elsif ($num == 1){
        return "ls";
    }
}

sub next_level {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)/;
    $user =~ s/\d//g;
    $user = $user . ++$num;
     return $user;
}

$command = next_command($username);
print $command . "\n";
$username = next_level($username);
$command = next_command($username);
print $command . "\n";

标量上下文中的匹配运算符的计算结果为布尔值,指示匹配是否成功。

my $success = $user =~ /(\d+)/;

列表上下文中的匹配运算符 returns 成功时捕获的字符串(或 1 如果没有捕获)和错误时的空列表。

my ($num) = $user =~ /(\d+)/;

你用的是前者,但你想要后者。这为您提供了以下内容(在其他一些小修复之后):

sub next_level {
    my ($user) = @_;
    my ($num) = $user =~ /(\d+)\z/;
    $user =~ s/\d+\z//g;
    $user .= ++$num;
    return $user;
}

但这种方法复杂且效率低下。更简单的解决方案:

sub next_level {
    my ($user) = @_;
    $user =~ s/(\d+)\z/  + 1 /e;
    return $user;
}