Perl matching operator

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.
To print this matched pattern and the remaining string, m operator provides various operators which include $, which contains whatever the last grouping match matched.
$& – contains the entire matched string
$` – contains everything before the matched string
$’ – contains everything after the matched string

Syntax: m/String/

Return:
0 on failure and 1 on success

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
# Text String
$string = "Geeks for geeks is the best";
  
# Let us use m operator to search 
# "or g"
$string =~ m/or g/;
  
# Printing the String
print "Before: $`\n";
print "Matched: $&\n";
print "After: $'\n";

chevron_right


Output:

Before: Geeks f
Matched: or g
After: eeks is the best

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
  
# Text String
$string = "Welcome to GeeksForGeeks";
  
# Let us use m operator to search 
# "to Ge"
$string =~ m/to Ge/;
  
# Printing the String
print "Before: $`\n";
print "Matched: $&\n";
print "After: $'\n";

chevron_right


Output:

Before: Welcome 
Matched: to Ge
After: eksForGeeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.