Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use m! in Perl regex

Tags:

regex

perl

I'm learning Perl and about regular expressions for the first time so I apologize if this is a dumb question. I've been searching to find the answer for this myself but can't find anything. Maybe part of my problem is that I really don't know what it's called.

I came across a piece of code that looked like this:

$xl_file = "$curr_dir/$xl_file" unless $xl_file =~ ( m!(^[a-z]:)|[/\\]!i );

When I looked into the =~ operator I dove into the regex hole and started learning about that. But I only ever saw the "m//" matching operator. I'm assuming "m!" is another kind of matching operator but I can't find any references to it that explain how it works. Through experimentation i see that the "!i" is required when using it but that's about as much as I could figure out...

Could someone please explain this to me, or point me in the direction of some (free) material that can?

like image 519
Gaax Avatar asked Dec 27 '22 01:12

Gaax


2 Answers

With matching operator, you can use any kind of delimiter, not just /.

So, all the below match operators are valid and do the same task:

m//
m!!
m{}
m##

Also note that, if you are using / as delimiter, you can remove that m from the beginning. So, /foo/ is valid, but !foo! is not.

like image 98
Rohit Jain Avatar answered Jan 11 '23 22:01

Rohit Jain


No, it is the exact same thing. In Perl, you can choose regex delimiters as you like. That is,

m/foo/
/foo/
m!foo!
m"foo"
m+foo+
m xfoox
m{foo}

are all the same regex (but never use question marks as delimiter, they wake an ancient demon).

After the closing delimiter, regex modifiers are placed. The /i modifier activates case-insensitive matching.

For the full blast, you can dive into perlre for all the hidden nuggets of Perl regexes. But for the start, perlretut should be more appropriate.

like image 34
amon Avatar answered Jan 11 '23 22:01

amon