从字符串捕获的Perl数字始终为1

时间:2017-11-15 13:54:05

标签: perl digits

在我开始学习的旅程中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

2 个答案:

答案 0 :(得分:3)

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

ng serve

列表上下文中的匹配运算符会在成功时返回捕获的字符串(如果没有捕获,则返回my $success = $user =~ /(\d+)/; ,并在出错时返回空列表。

1

你使用前者,但你想要后者。这给你以下(经过一些其他小修复):

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

但这种方法既复杂又低效。更简单的解决方案:

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

答案 1 :(得分:2)

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

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