perl function qr
The qr
function in Perl is used to compile a regular expression pattern into a regex object that can be used later for pattern matching or substitution. It returns a reference to the compiled regex object. Here's an example:
my $string = "The quick brown fox jumps over the lazy dog"; my $pattern = qr/quick (\w+) jumps/; if ($string =~ $pattern) { print "Found: $1\n"; } else { print "Pattern not found.\n"; }
In this example, we first define a string that contains a sentence. We then use the qr
function to compile a regular expression pattern that matches the word following "quick" and preceding "jumps". The parentheses in the pattern capture the matched word, which we can retrieve later using $1
. We then use the =~
operator to match the pattern against the string, and if it matches, we print the captured word. Otherwise, we print a message saying the pattern was not found.