为什么我只得到第一个捕获组? [英] Why do I get the first capture group only?

查看:47
本文介绍了为什么我只得到第一个捕获组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

(https://stackoverflow.com/a/2304626/6607497 and https://stackoverflow.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).

这篇关于为什么我只得到第一个捕获组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆