Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of qr// in perl

Tags:

regex

perl

I am completely new to perl and trying to design a lexer where I have come across:

my @token_def =
 (
        [Whitespace => qr{\s+},     1],
        [Comment    => qr{#.*\n?$}m,   1],
  );

and even after going through multiple sites I did not understand the meaning.

like image 690
bansal Avatar asked May 07 '15 06:05

bansal


2 Answers

qr// is one of the quote-like operators that apply to pattern matching and related activities.

From perldoc:

This operator quotes (and possibly compiles) its STRING as a regular expression. STRING is interpolated the same way as PATTERN in m/PATTERN/. If ' is used as the delimiter, no interpolation is done.

From modern_perl:

The qr// operator creates first-class regexes. Interpolate them into the match operator to use them:

my $hat = qr/hat/;
say 'Found a hat!' if $name =~ /$hat/;

... or combine multiple regex objects into complex patterns:

my $hat   = qr/hat/;
my $field = qr/field/;

say 'Found a hat in a field!'
if $name =~ /$hat$field/;

like( $name, qr/$hat$field/,
            'Found a hat in a field!' );
like image 59
serenesat Avatar answered Sep 28 '22 15:09

serenesat


qr// is documented in perlop in the "Regexp Quote-Like Operators" section.

Just like qq"..." aka "..." allows you to construct a string, qr/.../ allows you to construct a regular expression.

$s = "abc";     # Creates a string and assigns it to $s
$s = qq"abc";   # Same as above. 
print("$s\n");

$re = qr/abc/;   # Creates a compiled regex pattern and assigns it to $x
print "match\n" if $s =~ /$re/;

The quoting rules for qr/.../ are very similar to qq"..."'s. The only difference is that \ followed by a non-word character are passed through unchanged.

like image 22
ikegami Avatar answered Sep 28 '22 16:09

ikegami