Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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: (<>), 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.

like image 329
Jon Avatar asked Nov 28 '22 10:11

Jon


1 Answers

$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.

like image 69
Blagovest Buyukliev Avatar answered Dec 15 '22 06:12

Blagovest Buyukliev