ruggedbuteducated
ruggedbuteducated

Reputation: 1358

What is the use of the ampersand in regular expressions in Perl

Guys I have this regular expression in Perl which I don't understand.

s/\w+$/($`!)$&/;

The original string was

"huge dinosaur"

After that regular expression is executed, the string is now:

"huge (huge !)dinosaur"

I quite dont understand how that happened. And I don't understand what the ampersand is doing there. I understand the $`, but why is it that it's there, from what i know the $` takes the value before the match, which is i think nothing because there is no matching expression before the that regular expression above.

If somebody can link me to some very helpful tutorial on regular expressions on Perl is really appreciated.

Thanks

EDIT: I understand now what the ampersand means, it saves the match and the $` saves the value before the match, Now what i dont understand again is this whole part:

($`!)$&

how did this part became

(huge !)

Upvotes: 28

Views: 18097

Answers (2)

sidyll
sidyll

Reputation: 59297

You're correct, $` is a special variable which holds the contents before the match. $& is similar, but holds what was matched and $' holds what was after the match.

In "huge dinosaur", /\w+$/ matches dinosaur. So the variable contents are:

$` => "huge "
$& => "dinosaur"
$' => ""

Note that what was matched is dinosaur. Then it's replacing the dinosaur portion of the string with an opening parens, "huge ", exclamation mark, closing parens and finally dinosaur (what was matched).

Check the Perl documentation for perlvar and perlre.

Upvotes: 32

Eric S
Eric S

Reputation: 1363

$& (dollar ampersand) holds the entire regex match.

$' (dollar followed by an apostrophe or single quote) holds the part of the string after (to the right of) the regex match.

$` (dollar backtick) holds the part of the string before (to the left of) the regex match.

For more info, please consult http://www.regular-expressions.info/perl.html

Upvotes: 17

Related Questions