开发者

branch reset operator in perl 5.8.8

开发者 https://www.devze.com 2023-02-03 20:04 出处:网络
I wanted to know how can i write aregular expression compatible with Perl v5.8.8 and Perl v5.10.0 using branch rest operator?

I wanted to know how can i write a regular expression compatible with Perl v5.8.8 and Perl v5.10.0 using branch rest operator?

i have written a perl code with regexp in it and the code is working fine with Perl v5.10.0 but when i execute the same code with perl v5.8.8 on another machine it gives following 开发者_开发知识库error;

Sequence (?|...) not recognized in regex; marked by <-- HERE in ...

here is the code;

#!/usr/bin/perl -w

my $i = "[1284336000] NEW SERVICE STATE: snpv3;service1;HIGH;SAFE;1;warnings";

if($i =~ /^\[\d+\]\sNEW\sSERVICE\sSTATE:\s(?|(snpv1);(service1)|(snpv1);(service2)|(snpv2);(service2)|(snpv3);(service1)|(snpv3);(service3)|(snpv4);(service4)|(snpv5);(service4)|(snpv6);(service6)|(snpv7);(service7));(HIGH);(\w+);(\d).+$/){
    print "matched\n";
}
else{
    print "not matched\n";
}

Could anyone suggest how to make a regexp which is compatible to either version.

thanks


The branch reset operator isn't available until Perl 5.10 (as per man perlre), so if 5.8 is a requirement you'll have to write the regex without it.


The (?|...) branch reset operator was added in Perl 5.10. If you want to make your regex backwards-compatible with earlier versions of Perl you'll need to modify it to remove the construct.

Here's your current pattern, written using the /x modifier for legibility:

my $pattern = qr/
    ^
    \[\d+\]
    \s
    NEW\sSERVICE\sSTATE:
    \s
    (?|
          (snpv1);(service1)
        | (snpv1);(service2)
        | (snpv2);(service2)
        | (snpv3);(service1)
        | (snpv3);(service3)
        | (snpv4);(service4)
        | (snpv5);(service4)
        | (snpv6);(service6)
        | (snpv7);(service7)
    )
    ;
    (HIGH);
    (\w+);
    (\d)
    .+
    $
/x;

Are the specific combinations of snpv and service important to a match/non-match? If not, it's easy to get rid of the (?|...) construct.

my $pattern = qr/
    ^
    \[\d+\]
    \s
    NEW\sSERVICE\sSTATE:
    \s
    (snpv\d);
    (service\d);
    (HIGH);
    (\w+);
    (\d)
    .+
    $
/x;

If the combinations are important you could still use this pattern, but you'd need to do a follow-up check.

my %valid = (
    snpv1 => { service1 => 1, service2 => 1 },
    snpv2 => { service2 => 1 },
    snpv3 => { service1 => 1, service3 => 1 },
    snpv4 => { service4 => 1 },
    snpv5 => { service4 => 1 },
    snpv6 => { service6 => 1 },
    snpv7 => { service7 => 1 },
);

if ($i =~ $pattern && $valid{$1}{$2}) {
    # match
}
else {
    # no match
}
0

精彩评论

暂无评论...
验证码 换一张
取 消