Reputation: 171
If I want to find a specific (constant) string in another string, does the =~ do the job or is it better to use another operator? Should I use /^ $/?
use constant {
MYSTR => "HGjfslT",
};
if (MYSTR =~ $rec_str){
...
}
Cheers,
Carol
Upvotes: 0
Views: 1031
Reputation: 6798
While regex can do what you want, you may want to try the index function because that is specifically what the function is for and it is faster than regex. Use regex for more complex pattern matching.
if ( index( MYSTR, $rec_str ) != -1 ) {
....
}
Doing /^ $/
in the regex is to get an exact match. In that case, use eq
:
if ( MYSTR eq $rec_str ) {
...
}
Upvotes: 2
Reputation: 21666
=~
is perfectly fine for this type of task.
If you want the exact match then use ^
and $
to match the start and end.
use constant {
MYSTR => "HGjfslT",
};
my $rec_str = "jfslT";
if (MYSTR =~ /$rec_str/){
print "Matches!";
}
if (MYSTR =~ /^$rec_str$/){
print "This will not match!";
}
$rec_str = "HGjfslT";
if (MYSTR =~ /^$rec_str$/){
print "This will match!";
}
Upvotes: 0