in reply to Regex - Is there any way to control when the contents of a variable are interpolated? (Using "$1" and '$1' in regex replacements)

Hi, I am not sure that I understand what you want to do, but I am sure that I really don't understand why you are making things so complicated. Please explain what you want to do, or what result you want to obtain.

May be you want to try simply this:

!/usr/bin/perl use warnings; use strict; $_ = "a { b } c ( d ) e"; my $nobrackets = qr/([^{}]+)/; s/\{$nobrackets\}/leftbracket $1 rightbracket/g; print "$_\n";
which prints:
a leftbracket b rightbracket c ( d ) e
which is presumably what you want. Is this right? Or do you have something else in mind?

The would be easier ways to obtain the same result (such as changing the curlies only, rather than a combination of curlies and text), but I tried to stay close to what you have.

Update : Based on your update on Mar 15, 2014 at 05:33 UTC, I now understand that you had this complicated way of doing things simply because you wanted to do the replacement in a subroutine. You might modify the above in the following way:

use warnings; use strict; my @c = ("a { b } c ( d ) e", "a { b } c ( d ) e {{F}} ((G))"); print replace($_), "\n" for @c; sub replace { my $d = shift; my $nobrackets = qr/([^{}]+)/; $d =~ s/\{$nobrackets\}/leftbracket $1 rightbracket/g; return $d; }
which gives the following output:
a leftbracket b rightbracket c ( d ) e a leftbracket b rightbracket c ( d ) e {leftbracket F rightbracket} +((G))

  • Comment on Re: Regex - Is there any way to control when the contents of a variable are interpolated? (Using "$1" and '$1' in regex replacements)
  • Select or Download Code