What is the meaning of qr // in perl

I am completely new to perl and trying to create a lexer where I came across:

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

and even after going through several sites I did not understand the point.

+6
source share
2 answers

qr// is one of the quotation operators applicable to pattern matching and related actions.

From perldoc :

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

From modern_perl :

The qr // operator creates first-class regular expressions. Interpolate them into a mapping 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!' ); 
+7
source

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

Just as qq"..." aka "..." allows you to build a string, qr/.../ allows you to create 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 citation rules for qr/.../ very similar to qq"..." . The only difference is that \ followed by a non-word character is passed unchanged.

+4
source

Source: https://habr.com/ru/post/986707/


All Articles