13

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.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
bansal
  • 227
  • 1
  • 3
  • 9

2 Answers2

21

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!' );
RobEarl
  • 7,862
  • 6
  • 35
  • 50
serenesat
  • 4,611
  • 10
  • 37
  • 53
5

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.

mpapec
  • 50,217
  • 8
  • 67
  • 127
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • After using `$re = qr/abc/`, it seems like you can just do `$s =~ $re` without the forward-slashes, since the forward-slashes are effectively compiling the regex and you have have already done that with `qr`. – CJ7 Oct 23 '20 at 06:04
  • @CJ7 yup, just like you can do `$s =~ "abc"`. In the absence of a qr//, m//, s/// or tr/// operator, a match operator (m//) is implied by the binding operator. But no, `/$re/` doesn't recompile the regex. – ikegami Oct 23 '20 at 06:13