What does =~ do in Perl?

Go To StackoverFlow.com

19

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
}
2012-04-04 20:51
by Invictus
If you want to spend a few minutes learning about regular expressions in Perl have a look at perlrequick - Sebastian Stumpf 2012-04-04 21:00
Learning Perl explains it all : - brian d foy 2012-04-04 23:38


25

=~ 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".

2012-04-04 20:56
by jmhl
You mean if there is a space in between it does not work... for example... 9sssbt yyuuiihh 88880099 9eaf 888hhjjj nnmmmm. Will the above logic for this string?? - Invictus 2012-04-04 21:07
No, m// is the operationoperator testing the regex. =~ simply tells m// (and s/// and tr//) which variable to test against - ikegami 2012-04-04 21:53
No, /9eaf/ is not the regular expression. /9eaf/ is the match operator. 9eaf is the regular expression - ikegami 2012-04-04 21:54


8

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.

2012-04-04 21:01
by NoName


5

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.

2012-04-04 21:57
by ikegami


3

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.

2012-04-04 20:56
by NoName
You mean if there is a space in between it does not work... for example... 9sssbt yyuuiihh 88880099 9eaf 888hhjjj nnmmmm. Will the above logic for this string?? - Invictus 2012-04-04 21:09
Why don't you try it for yourself - NoName 2012-04-04 21:38
Ads