What does =~ do in Perl? [closed]
I guess the tag is a variable, and it is checking for 9eaf
- but does this exist in Perl?
What is the "=~" sign doing here and what are the "/" characters before and after 9eaf
doing?
if ($tag =~ /9eaf/)
{
# Do something
}
Solution 1:
=~
is the operator testing a regular expression match. The expression /9eaf/
is a regular expression (the slashes //
are delimiters, the 9eaf
is the actual regular expression). In words, the test is saying "If the variable $tag matches the regular expression /9eaf/ ..." and this match occurs if the string stored in $tag
contains those characters 9eaf
consecutively, in order, at any point. So this will be true for the strings
9eaf
xyz9eaf
9eafxyz
xyz9eafxyz
and many others, but not the strings
9eaxxx
9xexaxfx
and many others. Look up the 'perlre' man page for more information on regular expressions, or google "perl regular expression".
Solution 2:
The '=~' operator is a binary binding operator that indicates the following operation will search or modify the scalar on the left.
The default (unspecified) operator is 'm' for match.
The matching operator has a pair of characters that designate where the regular expression begins and ends. Most commonly, this is '//'.
Give Perl Re tutorial a read.
Solution 3:
The code is testing whether 9eaf
is a substring of the value of $tag
.
$tag =~ /9eaf/
is short for
$tag =~ m/9eaf/
where m//
is the match operator. It matches the regular expression pattern (regexp) 9eaf
against the value bound by =~
(returned by the left hand side of =~
).
Operators, including m//
and =~
, are documented in perlop.
Regular expressions (e.g. 9eaf
) are documented in perlre, perlretut.
Solution 4:
That checks for a match of the scalar $tag
(which is presumably a string) against the regular expression /9eaf/
, which merely checks to see if the string "9eaf"
is a substring of $tag
. Check out perldoc perlretut
.