开发者

Perl: Why would eq work, when =~ doesn't?

开发者 https://www.devze.com 2023-03-12 06:03 出处:网络
Working code: if ( $check1 eq $search_key ... Previous \'buggy\' code: if ( $check1 =~ /$search_key/ ...

Working code:

if ( $check1 eq $search_key ...

Previous 'buggy' code:

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

The words (in $check1 and $search_key) should be the same, but why doesn't the 2nd one return true all the time? What is different about these?

$check1 is acquired through a split. $search_key is either inputted before ("word") or at runtime: (<>开发者_JS百科), both are then passed to a subroutine.

A further question would be, can I convert the following with without any hidden problems?

if ($category_id eq "subj") {

I want to be able to say: =~ /subj/ so that "subject" would still remain true.

Thanks in advance.


$check1 =~ /$search_key/ doesn't work because any special characters in $search_key will be interpreted as a part of the regular expression.

Moreover, this really tests whether $check1 contains the substring $search_key. You really wanted $check1 =~ /^$search_key$/, although it's still incorrect because of the reason mentioned above.

Better stick with eq for exact string comparisons.


as mentioned before, special characters in $search_key will be interpreted, to prevent this, use \Q: if ( $check1 =~ /\Q$search_key/), which will take he content of $search_key as a literal. You can use \E to end this if ( $check1 =~ /\b\Q$search_key\E\b/) for example.

This information is in perlre


Regarding your second question, if just you want plain substring matching, you can use the index function. Then replace

if ($category_id eq "subj") {

with

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

This is a case-sensitive match.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消