headache
headache

Reputation: 133

Regex inconsistent

Using Resultset from my DB....

my $item_name = "Special Anniversary set by Brand Name"
my $item_name1 = $item_name;
$item_name1 =~ m/brand name/i;
$brand = $&; # a system var of the regex result

Brand outputs correctly: 'Brand Name'

my $item_name2 = $item_name;
$item_name2 =~ m/Special Anniversary by brand_name/i;
$sub_brand = $&; # a system var of the regex result

Sub brand outputs wrongly/inconsistently.

if ( $item_name eq 'Special Anniversary set by Brand Name' )
{
$brand outputs as 'Brand Name'; # correct
$sub_brand outputs as 'Special anniversary by Brand Name'; #correct
}
elsif( $item_name eq 'Something else by Brand Name' )
{
$brand outputs as 'Brand Name';# correct
$sub_brand = 'Brand Name'; #INCORRECT  I expect it to be null.

}  

I hope that is sufficiently concise yet understandable.

However, in case not, the sub brand is returning the brand name (or perhaps the end of the desired string), if it doesn't match.

I guess it's returning the $& value from the first regex because it hasn't been overwritten with a match on the second regex.

I would appreciate any suggestions you may have.

Upvotes: 0

Views: 71

Answers (1)

ikegami
ikegami

Reputation: 385575

I guess it's returning the $& value from the first regex because it hasn't been overwritten with a match on the second regex.

That is correct.

I would appreciate any suggestions you may have.

Since you only want to use $& is the match was successful, check if the match was successful before using $&.

my $sub_brand;
if ($item_name2 =~ /Special Anniversary by brand_name/i) {
   $sub_brand = $&;
}

or

my $sub_brand = $item_name2 =~ /Special Anniversary by brand_name/i ? $& : undef;

You could also use

my ($sub_brand) = $item_name2 =~ /(Special Anniversary by brand_name)/i;

Upvotes: 1

Related Questions