Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between /.../ and m/.../ in Perl

Tags:

perl

What is difference between /.../ and m/.../?

use strict;
use warnings;

my $str = "This is a testing for modifier";

if ($str =~ /This/i) { print "Modifier...\n";  }
if ($str =~ m/This/i) { print "W/O Modifier...\n";  }

However, I checked with this site for Reference not clearly understand with the theory

like image 319
ssr1012 Avatar asked Jul 04 '17 12:07

ssr1012


2 Answers

There's no difference. If you just supply /PATTERN/ then it assumes m. However, if you're using an alternative delimiter, you need to supply the m. E.g. m|PATTERN| won't work as |PATTERN|.

In your example, i is the modifier as it's after the pattern. m is the operation. (as opposed to s, tr, y etc.)

Perhaps slightly confusingly - you can use m as a modifier, but only if you put if after the match.

m/PATTERN/m will cause ^ and $ to match differently than in m/PATTERN/, but it's the trailing m that does this, not the leading one.

like image 102
Sobrique Avatar answered Sep 20 '22 17:09

Sobrique


Perl has a number of quote-like operators where you can choose the delimiter to suit the data you're passing to the operator.

  • q(...) creates a single-quoted string
  • qq(...) creates a double-quoted string
  • qw(...) creates a list by splitting its arguments on white-space
  • qx(...) executes a command and returns the output
  • qr(...) compiles a regular expression
  • m(...) matches its argument as a regular expression

(There's also s(...)(...) but I've left that off the list as it has two arguments)

For some of these, you can omit the letter at the start of the operator if you choose the default delimiter.

  • You can omit q if you use single quote characters ('...').
  • You can omit qq if you use double quote characters ("...").
  • You can omit qx if you use backticks (`...`).
  • You can omit m if you use slashes (/.../).

So, to answer your original question, m/.../ and /.../ are the same, but because slashes are the default delimitor for the match operator, you can omit the m.

like image 44
Dave Cross Avatar answered Sep 20 '22 17:09

Dave Cross