Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curly brackets in regexps with Perl

Tags:

regex

perl

just trying to get my head around regexps. The following is part of the code. It read a file line by line and it has the following expression to trip the line of white spaces at either end.

\A match the start of the line
\s+ one or more white spaces
\z match the end of the line

while (<$fh>) 
{
  s{\A\s+}{};
  s{\s+\z}{};
}

The part I am struggling with is the curly brackets. The only documentation I can find on them states they act as a multiplier. I read s{\A\s+}{}; if start of line AND white spaces replace with nothing, but that's my guess. I am looking to confirm that and what the curly brackets means in this regexps

like image 628
alexis Avatar asked Feb 14 '23 11:02

alexis


2 Answers

devnull has already given the correct answer, but I felt there was more to add than fits in a comment.

s{}{} is simply the s/// substitution operator, but used with a different delimiter. You can use just about any character as delimiter, including balanced parentheses of different types, e.g. s#foo#bar#, s[foo][bar].

You use this to avoid escaping delimiters in the matching string. Such as when matching paths:

s#/foo/bar/baz#/foo/baz/bax#

Looks better than the equivalent, using the default slash delimiter /:

s/\/foo\/bar\/baz/\/foo\/baz\/bax/

Which honestly is quite confusing.

In your case, there is no real reason to use a different delimiter, so the substitutions are in my opinion best written with the original delimiter:

s/\A\s+//
s/\s+\z//
like image 149
TLP Avatar answered Feb 24 '23 10:02

TLP


The {} refer to a pair of delimiters.

You might want to refer to Quote and Quote-like Operators.

 Customary Generic Meaning  Interpolates
            s{}{}  Substitution yes*

As an example:

$ echo foo 42 bar | perl -pe 's{42}{84}'
foo 84 bar
like image 24
devnull Avatar answered Feb 24 '23 09:02

devnull