是否可以使用perl中的oneliner将多个分组值推入多个离散数组?

时间:2015-03-18 06:05:15

标签: arrays regex perl

我有一个perl正则表达式,我必须将$1$2以及3推送到三个独立的数组中。

目前我正在将$1推送到3个单独的语句中,如下所示:

foreach (@time){
    push @hour, $1 while $_ =~ /(\d\d):\d\d:\d\d/g;
    push @minute, $1 while $_ =~ /\d\d:(\d\d):\d\d/g;
    push @second, $1 while $_ =~ /\d\d:\d\d:(\d\d)/g;
}

我知道可以像这样指定标量变量:

my ($i, $j, $k) = $time =~ /(\d\d):(\d\d):(\d\d)/;

以相同的方式执行数组将所有组存储到第一个数组中。

my (@i, @j, @k) = $time =~ /(\d\d):(\d\d):(\d\d)/g;
print "@i \n";
print "------- \n";
print "@j \n";
print "------- \n";
print "@k \n";
print "------- \n";

返回:

12 23 43 15 33 54 00 12 23    
-------

-------

-------

有没有办法像标量变量一样将组推入单个数组中的单独数组?

编辑:

$time = "12:23:54
15:33:54
00:12:23";

1 个答案:

答案 0 :(得分:1)

您不需要多次匹配。

my $time = "12:23:54\n15:33:54\n00:12:23";
my (@hour, @minute, @second);
while ($time =~ /(\d\d):(\d\d):(\d\d)/g) {
    push @hour,   $1;
    push @minute, $2;
    push @second, $3;
}

我不建议像

这样的东西
1 while $time =~ /(\d\d):(\d\d):(\d\d)(?{ push @hour,   $1;
                                          push @minute, $2;
                                          push @second, $3
                                        })/g;

因为它的可读性低得多。

以下内容可能更具可读性,但我仍然会采用第一种解决方案。

my @matches = $time =~ /(\d\d):(\d\d):(\d\d)/g;
($hour[@hour], $minute[@minute], $second[@second])
    = splice @matches, 0, 3 while @matches;