Reputation: 7959
I came across this awesome regex:
s/((?:\\[a-zA-Z\\])+)/qq[qq[$1]]/eeg
It does magic, but is so obscure I can't understand it. It works very well:
echo 'a\tb\nc\r\n' | perl -lpe 's/((?:\\[a-zA-Z\\])+)/qq[qq[$1]]/eeg'
a b
c
Let us watch it with cat -A
:
echo 'a\tb\nc\r\n' | perl -lpe 's/((?:\\[a-zA-Z\\])+)/qq[qq[$1]]/eeg' | cat -A
a^Ib$
c^M$
$
I will keep it for future reference, but it would be really cool to understand it. I know /ee
modifier evaluates RHS
, but what are those qq
s? Is the function qq
for double quotes ? I would appreciate if someone could explain.
PS. I found this regex here
Upvotes: 0
Views: 464
Reputation: 17710
qq
is the interpolating quote operator. It's the same thing as putting a string between double quotes, but can use open-close character pairs like []
here. This has the advantage that you can nest it, which you couldn't do with double quotes.
Upvotes: 1
Reputation: 1416
In perl re's you have single and double quotes, where "$foo" is expanded and '$foo' is literal.
The q
operator lets you set which character does '
The qq
operator sets the character for "
.
So in the awesome example, [
is getting set to expand variables, and perl magic is making it more readable by pairing ]
with [
. So it's expanding the variable twice, which without that highlighting would be deeply mysterious, and the "
quotes get very confusing when mixed in with shell quoting.
A simple example to try out :
% perl -E '$foo=bar; say qq[$foo];'
bar
%
Upvotes: 1