Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why $_ =~ "regular expression" is valid in Perl?

Tags:

perl

I know in Perl, a most common valid regular expression is like this:

$_ =~ m/regular expression/;

# and "m" can be omit
$_ =~ /regular expression/;

And I can use qr to create a regular expression reference like this:

my $regex = qr/regular expression/;
$_ =~ m/$regex/;

# and "m//" can be omit:
$_ =~ $regex;

But I have tried this:

my $str = "regular expression";
$_ =~ $str; # why this is valid?

It didn't give me any error infomation and worked fine. I don't know why, I think it should be like:

my $str = "regular expression";
$_ =~ m/$str/;

# or
my $str = "regular expression";
my $regex = qr/$str/;
$_ =~ $regex;

Can anyone explain why $_ =~ $str is valid in Perl?

like image 842
Lane Avatar asked Dec 13 '22 14:12

Lane


1 Answers

It says under "The basics" in perlre

Patterns that aren't already stored in some variable must be delimitted, at both ends, by delimitter characters.

( along with the incorrect double-t in delimite(d/r) )

Thus, a pattern in a variable just doesn't need delimiters. The operator =~ discussed in "Binding operators" in perlop

binds a scalar expression to a pattern match.

and (with my emphasis)

If the right argument is an expression rather than a search pattern, substitution, or transliteration, it is interpreted as a search pattern at run time.

The operator doesn't care for delimiters on its right hand side and a "regex pattern" can be formed at runtime out of an expression.

The section "Gory details of parsing quoted constructs" in perlop helps with this as well, apart from being illuminating in its own right. After the quoted construct is identified and the contained text interpolated it comes to the bullet "parsing regular expressions"

After preprocessing described above ... the resulting string is passed to the RE engine for compilation.

(my emphasis)

This is a general discussion of how Perl handles quoted constructs and there is no requirement for (extra) delimiters once the string is formed out of the quoted construct. The m/RE/ (etc) are discussed earlier in the "interpolation" bullet, what shows some of the things that can't be used with a plain string for a pattern, but that is clearly not compulsory to have.

I'd recommend against this though; use qr, as you expect. For one thing, using a string (and not a regex built with qr) is limiting. Also, it is more prone to silly errors.


Note that while for many patterns one can use either qr or "" (or its operator form qq()) to prepare the pattern (or the string which will be interpreted that way) -- they are not the same. Their quoting rules are quite similar but the qr prepares a regular expression which, as put in Regexp Quote-Like Operators

... magically differs from a string containing the same characters ...

For one, recall that with qr you may use modifiers.

like image 188
zdim Avatar answered Jan 14 '23 01:01

zdim