Perl: Why does eq work when = ~ not?

Work code:

if ( $check1 eq $search_key ... 

Previous 'buggy' code:

 if ( $check1 =~ /$search_key/ ... 

Words (in $check1 and $search_key ) should be the same, but why doesn't the second one return true all the time? What is their difference?

$check1 obtained through a split. $search_key either entered before ("word"), or at runtime: ( <> ), then both are passed to the subroutine.

One more question: is it possible to convert the following without any hidden problems?

 if ($category_id eq "subj") { 

I want to be able to say: =~ /subj/ so that the "object" is still true.

Thanks in advance.

+4
source share
3 answers

$check1 =~ /$search_key/ does not work, because any special characters in $search_key will be interpreted as part of the regular expression.

Also, it really checks if $check1 substring $search_key . You really wanted $check1 =~ /^$search_key$/ , although it is still incorrect due to the reason mentioned above.

Better stick to eq for exact string comparisons.

+12
source

as mentioned earlier, special characters in $ search_key will be interpreted to prevent this, use \Q : if ( $check1 =~ /\Q$search_key/) , which will contain the contents of $search_key as a literal. You can use \E to complete this if ( $check1 =~ /\b\Q$search_key\E\b/) , for example.

This information is in perlre

+11
source

As for your second question, if you want a simple substring, you can use the index function. Then replace

if ($category_id eq "subj") {

with

if (0 <= index $category_id, "subj") {

This is a case match.

Addition for clarification: it will match asubj , subj and even subjugate

+1
source

All Articles