Reputation: 567
Here is the code -
my $s_ver = 'port=":443"; d=3600; v="10,20"';
my $b_ver = 'FB10';
if ($s_ver =~ /(v="[0-9]+(,[0-9]+)*")/ && $b_ver =~ /FB(\d\d)/){
{
print("$1 and $2\n");
}
Current Output -
10 and
Expected output -
v="10,20" and 10
How can this be achieved? Thanks.
Upvotes: 1
Views: 101
Reputation: 386331
if (
( my ($s_cap) = $s_ver =~ /(v="[0-9]+(?:,[0-9]+)*")/ ) &&
( my ($b_cap) = $b_ver =~ /FB(\d\d)/ )
) {
print("$s_cap and $b_cap\n");
}
Upvotes: 4
Reputation: 1832
You should usually never try to retain and use the $number variables over long code distances. Long meaning 2 or 3 lines. You should always capture them to normal variables immediately. The reason is obvious from your attempt at subverting that wisdom.
Your attempt can't work because the $num match variables are localized and lexically scoped. One sucessful match clobbers any previous one. However a failed match does not reset them. Caveat emptor.
There are machinations you can do to get your two regex tests into a single if
but it's just not worth it.
Do this instead.
my $s_ver = 'port=":443"; d=3600; v="10,20"';
my $b_ver = 'FB10';
my $s_match = $s_ver =~ m/(v="[0-9]+(?:,[0-9]+)*")/ ? $1 : undef;
my $b_match = $b_ver =~ m/FB(\d\d)/ ? $1 : undef;
if ( defined $s_match and defined $b_match ) {
print("$s_match and $b_match\n");
}
HTH
Upvotes: 1