嵌套的perl匹配组不起作用?

时间:2017-06-23 18:39:10

标签: perl

我希望以下代码打印出“bye”,然后打印出“hello”。但是,当我运行它时,它打印出“再见”,然后perl告诉我$ str2尚未初始化。

 my $item = "hello/bye";
 if($item =~ m/.*(bye)/g){
     my $str1 = $1;
     print "$str1\n";
     my $str2 = ($item =~ m/(hello).*/g)[0];
     print "$str2\n";
 }

我认为可能有一些我不了解m // g部分的内容,但我在perldre页面中找不到perlre的答案。

1 个答案:

答案 0 :(得分:4)

当你这样做时

if($item =~ m/.*(bye)/g)

不重置匹配迭代器(我们在标量上下文中)。 “position”保留在bye子字符串后面的字符处。所以下面的m//g会从那里继续前进。{/ p>

您可以自行验证:

if ($item =~ /(bye)/g) {
    printf "pos \$item = %d\n", pos $item;
    ...
}

将打印pos $item =9

顺便说一句,$item =~ /.*(bye)/最好写成$item =~ /(bye)/(假设您不关心是否匹配第一个或最后一个bye子字符串,只需$item bye $item =~ /(hello).*/ 1}}某处)。同样,$item =~ /(hello)/最好写成#!/usr/bin/env perl use strict; use warnings; my $item = "hello/bye"; if ($item =~ /(bye)/) { my $str1 = $1; print "$str1\n"; my $str2 = ($item =~ /(hello)/g)[0]; print "$str2\n"; }

declare @table table(ID int, TestID int, Question1 int, Question2 int, Question3 int, EmployeeID int)
insert into @table
values
(1,1000,10,null,null,12),
(2,1000,10,7,null,12),
(3,1000,10,7,null,12),
(4,1000,10,7,null,12),
(5,1000,10,7,null,12),
(6,1000,10,7,null,5),
(7,1000,10,7,null,5),
(8,1000,10,7,null,5),
(9,1000,10,7,null,5),
(10,1000,10,7,null,5),
(11,1000,10,7,null,5),
(12,1000,10,7,null,5),
(13,1000,10,7,null,5),
(14,1000,10,null,null,5),
(15,1000,10,7,null,5),
(16,2000,5,10,10,3),
(17,2000,5,0,3,3),
(18,2000,null,9,8,6),
(19,2000,5,10,9,6),
(20,2000,null,10,9,7),
(21,2000,null,10,9,7)

;with cte as(
    select 
        TestID, 
        EmployeeID,
        max(Question1) as Q1,
        max(Question2) as Q2,
        max(Question3) as Q3
    from 
        @table
    group by
        TestID, 
        EmployeeID)

select 
    EmployeeID,
    TestID,
    Sum(isnull(Q1,0) + isnull(Q2,0) + isnull(Q3,0)) / min(case when Q1 is null then 0.0 else 1.0 end + case when Q2 is null then 0.0 else 1.0 end + case when Q3 is null then 0.0 else 1.0 end ) as AverageScore
from 
    cte
group by
    EmployeeID,
    TestID
order by
    TestID
    ,AverageScore