Score:0

Perl: replace literal expression and literal variable names

it flag

When I use this expression:

echo '...${var}#other.([]);,=${var}#other${var}...' | perl -pe 's/\Q.([]);,=${var}\E/.([]);,=ok/'

As expected, the variable ${var} is expanded to "" (empty value) and the output is obtained:

...${var}#other.([]);,=ok${var}#other${var}...

but I want:

...${var}#other.([]);,=ok#other${var}...

So I thought about escaping the variable:

echo '...${var}#other.([]);,=${var}#other${var}...' | perl -pe 's/\Q.([]);,=\${var}\E/.([]);,=ok/'

For some reason that I don't know, the supplied string doesn't match a portion of the input one and it doesn't get replaced:

...${var}#other.([]);,=${var}#other${var}...

Double \\$ and triple \\\$ backslashes don't match either.
Where did I go wrong?

Score:1
us flag

Looking at the documnentation for \Q in man perlop:

For the pattern of regex operators ("qr//", "m//" and "s///"), the quoting from "\Q" is
applied after interpolation is processed, but before escapes are processed.  This allows
the pattern to match literally (except for "$" and "@").  For example, the following
matches:

   '\s\t' =~ /\Q\s\t/

Because "$" or "@" trigger interpolation, you'll need to use something like
"/\Quser\E\@\Qhost/" to match them literally.

And, checking the doc for quotemeta (which is used to implement \Q ... \E internally) in man perlfunc:

Beware that if you put literal backslashes (those not inside interpolated variables)
between "\Q" and "\E", double-quotish backslash interpolation may lead to confusing
results.  If you need to use literal backslashes within "\Q...\E", consult "Gory
details of parsing quoted constructs" in perlop.

Because the result of "\Q STRING \E" has all metacharacters quoted, there is no way to
insert a literal "$" or "@" inside a "\Q\E" pair.  If protected by "\", "$" will be
quoted to become "\\\$"; if not, it is interpreted as the start of an interpolated
scalar.

So the $ can't be kept inside \Q ... \E. You'll have to do something like:

% echo '...${var}#other.([]);,=${var}#other${var}...' | perl -pe 's/\Q.([]);,=\E\$\Q{var}\E/.([]);,=ok/'
...${var}#other.([]);,=ok#other${var}...
it flag
Ok, perfect....
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.