开发者

Perl Regular Expression default for non-matched

Lets say I do this:

my ($a,$b,$let) = $version =~ m/^(\d+)\.(\d+)\.?([A-Za-z开发者_StackOverflow社区])?$/;

so this will match for instance: 1.3a, 1.3,... I want to have a default value for $let if let is not available, lets say, default 0. so for 1.3 I will get: $a = 1 $b = 3 $let = 0

is it possible? (from the regex it self, without using additional statements)

Thanks,


This will work - updated to use bitwise or instead of ternary operator.

my ($a,$b,$let) = ($version =~ m/^(\d+)\.(\d+)\.?([A-Za-z])?$/) 
            && ($1,$2,$3 || 0 );

Here is a test script

&t("1.3");
&t("1.3a");
&t("1.3.a");

sub t {
$version = shift;
my ($a,$b,$let) = ($version =~ m/^(\d+)\.(\d+)\.?([A-Za-z])?$/) 
                && ($1,$2,$3 || 0 );
print "\n result $a.$b.$let";
}

Output is

result 1.3.0
result 1.3.a
result 1.3.a

original solution using ternary operator also works

my ($a,$b,$let) = ($version =~ m/^(\d+)\.(\d+)\.?([A-Za-z])?$/) 
            && (defined $3 ? ($1,$2,$3) : ($1,$2,0));


$let should have a default value of undef. You can test on that if you need to.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜