为什么我只得到第一个捕获组?

问题描述:

(https://*.com/a/2304626/6607497https://*.com/a/37004214/6607497 没有帮助我)

(https://*.com/a/2304626/6607497 and https://*.com/a/37004214/6607497 did not help me)

在 Linux 中分析 /proc/stat 的问题 我开始编写一个小实用程序,但我无法按照我想要的方式获取捕获组.代码如下:

Analyzing a problem with /proc/stat in Linux I started to write a small utility, but I can't get the capture groups the way I wanted. Here is the code:

#!/usr/bin/perl
use strict;
use warnings;

if (open(my $fh, '<', my $file = '/proc/stat')) {
    while (<$fh>) {
        if (my ($cpu, @vals) = /^cpu(\d*)(?:\s+(\d+))+$/) {
            print "$cpu $#vals\n";
        }
    }
    close($fh);
} else {
    die "$file: $!\n";
}

例如,通过这些输入行,我得到了输出:

For example with these input lines I get the output:

> cat /proc/stat
cpu  2709779 13999 551920 11622773 135610 0 194680 0 0 0
cpu0 677679 3082 124900 11507188 134042 0 164081 0 0 0
cpu1 775182 3866 147044 38910 135 0 15026 0 0 0
cpu2 704411 3024 143057 37674 1272 0 8403 0 0 0
cpu3 552506 4025 136918 38999 160 0 7169 0 0 0
intr 176332106  ...

 0
0 0
1 0
2 0
3 0

所以匹配确实有效,但我没有将捕获组放入 @vals(perls 5.18.2 和 5.26.1).

So the match actually works, but I don't get the capture groups into @vals (perls 5.18.2 and 5.26.1).

替换

    while (<$fh>) {
        if (my ($cpu, @vals) = /^cpu(\d*)(?:\s+(\d+))+$/) {

    while (<$fh>) {
        my @vals;
        if (my ($cpu) = /^cpu(\d*)(?:\s+(\d+)(?{ push(@vals, $^N) }))+$/) {

做我想做的事(需要 perl 5.8 或更高版本).

does what I wanted (requires perl 5.8 or newer).