Satya Satya - 3 months ago 9
Perl Question

Not able to understand !~ in regex

My requirement is to pass a string with + (eg: ABC+DEF). And it should match with any value for actual_state, values can be

ABC+DEF ABC+DEF, ABC+DEF,,
etc .Here there can be one or more comma after ABC+DEF. But it should not match with
ABC+DEF, PQR-SL
.

Below is the code snippet what i tried:

sub verify_state{
my $expected_state = shift;
my $vol = 'vol';
my $actual_state = 'ABC+DEF,';
print "Verify backend state for $vol\n";
print "Expected backend state for $vol = $expected_state\n";
print "Actual backend state for $vol = $actual_state\n";
if ( $expected_state !~ /$actual_state,*$/ ) {
print
"Expected state was $expected_state but got $actual_state for $vol\n"
;
return 0;
}
return 1;
}

my $val = verify_state('ABC+DEF');
print $val,"\n";


it should return me 1 if i will pass
ABC+DEF
.
0 if i will pass
ABC+DEF, PQR-SL


why i wrote
my $actual_state = 'ABC+DEF,';

Because the values
ABC+DEF ABC+DEF, ABC+DEF,,
are coming as a part of a hash value for a specific key eg.
my $actual_state = $status->{state};
.

Answer

You have a comma , hardcoded in your $actual_state. So it cannot match the input you are testing with, ABC+DEF without a comma. The way you build the pattern you also need to escape the + (thanks to slebetman), so

my $actual_state = 'ABC\+DEF';

and the rest should work.

This assumes that your input must indeed end with that string, optionally followed only by commas.