I recently saw code from someone who is not familiar with Perl. He wanted to compare two lines for equality, but did not know about the eq operator, so he used =~ as follows:
my $str1 = 'foobar'; my $str2 = 'bar'; if ( $str1 =~ $str2 ) { print "strings are equal\n"; }
Another fragment was
if ( $str1 =~ "foo" ) { print "string equals 'foo'\n"; }
Of course, he should just read $str1 eq $str2 and $str1 eq "foo" to avoid false positives.
I run the code through Deparse , and he said that everything is fine:
$ perl -MO=Deparse -e 'use strict; use warnings; my $str1="foobar"; my $str2="bar"; $str1 =~ $str2; $str1 =~ "bar";' use warnings; use strict; my $str1 = 'foobar'; my $str2 = 'bar'; $str1 =~ /$str2/; $str1 =~ /bar/; -e syntax OK
I looked through the docs , but from my understanding the situation is this:
- The general syntax is
m/pattern/ . - Use
m and the separator of your choice instead of / (but keep in mind that ' and ? Have special meaning) - Or leave
m , but the separator should be / .
But, apparently, Perl understands $str1 =~ "foo" as $str1 =~ m/foo/ , although there is no m . Why is this? I expected this to be a syntax error.
regex perl
Perlduck
source share