[ale] perl question: eval'ing variable as s/// pattern match

Brian Pitts brian at polibyte.com
Sat Jan 12 21:45:42 EST 2008


Chris Woodfield wrote:
> As I emailed Jim privately, right solution, wrong problem :( The goal is 
> to make the second version of this code work the same as the first...
> 
> s/(pattern)/add stuff to $1/;
> 
> currently this returns "add stuff to pattern"
> 
> and
> 
> $matchtext = '(pattern)';
> $replacetext = 'add stuff to $1';
> s/$matchtext/$replacetext/;
> 
> this returns "add stuff to $1", and doesn't eval the $1 var. Anyone know 
> how to make it do this?
> 
> -C

Probably not helpful to you, but out of curiosity I decided to see how 
Ruby regular expressions [1] would handle this. Although Ruby has an 
object oriented Regexp system, it sets the $-variables after each 
pattern match to keep perl hackers happy. However, within the pattern or 
replacement string you have to use the \-sequences.

text = 'test'
test = /(test)/
match = 'matched \1'

puts 'Testing direct match:'
puts text.sub(test, 'matched \1')

puts 'Testing var match:'
puts text.sub(test, match)

The output is

Testing direct match:
matched test
Testing var match:
matched test

-Brian

[1] http://www.rubycentral.com/pickaxe/tut_stdtypes.html



More information about the Ale mailing list