APM: Regular expression with double variable substitution

Mike Stok mike at stok.co.uk
Sat Jan 7 14:40:19 PST 2006


On 6-Jan-06, at 4:55 PM, Evan Harris wrote:

>
> After talking with Wayne, I think I've settled on a workable  
> (though not
> optimal) solution:
>
> my $cmd = '$str =~ s/' . $srcregex . '/' . $dstregex . '/';
> eval $cmd;
>
> I was trying to avoid using eval, but I can't figure out how.  It  
> seems
> really strange that perl doesn't provide a way to use the contents  
> of a
> variable in a way that perl will do one more level of variable  
> expansion.


If you don't want eval then you can use extra e modifiers e.g. (in  
the debugger)

   DB<1> $s = '$1 - $2'

   DB<2> $t = '34:56'

   DB<3> $t =~ s/(\d+):(\d+)/'"' . $s . '"'/ee

   DB<4> print $t
34 - 56

the "first" e turns the right hand side into "$1 - $2", and the  
second does the double quotish interpolation.

Hope this helps,

Mike


>
> Evan
>
>
> On Fri, 6 Jan 2006, Fluhmann, Jeremy wrote:
>
>> This works, but I'm not sure it's what you're trying to do.
>>
>> $t = '34:56';
>> $t =~ s/(\d+):(\d+)/"$1 - $2"/e;
>>
>> Jeremy Fluhmann
>> Microcomputer Specialist
>> Department of Student Activities
>> Texas A&M University
>> 979-458-4649
>> jeremy at stuact.tamu.edu
>>
>> -----Original Message-----
>> From: austin-bounces at pm.org [mailto:austin-bounces at pm.org] On  
>> Behalf Of
>> Evan Harris
>> Sent: Friday, January 06, 2006 2:05 PM
>> To: Austin Perlmongers
>> Subject: APM: Regular expression with double variable substitution
>>
>>
>> Is there any way to make perl re-interpret the contents of a variable
>> that
>> is used as a substitution part of a regex?  I thought that the /e
>> modifier
>> would do this, but it doesn't seem to work.
>>
>> For example:
>>
>> $s = '$1 - $2';
>> $t = '34:56';
>> $t =~ s/(\d+):(\d+)/$s/e;
>>
>> After this, $t is equal to '$1 - $2', rather than the desired '34  
>> - 56'.
>>
>> I think it may be possible by using an eval, but I don't want the  
>> power
>> (and
>> the danger) of allowing any perl code, I just want to fill in nested
>> variables.
>>
>> Evan
>>
>>
>> _______________________________________________
>> Austin mailing list
>> Austin at pm.org
>> http://mail.pm.org/mailman/listinfo/austin
>>
>>
>> _______________________________________________
>> Austin mailing list
>> Austin at pm.org
>> http://mail.pm.org/mailman/listinfo/austin
>>
>
>
> _______________________________________________
> Austin mailing list
> Austin at pm.org
> http://mail.pm.org/mailman/listinfo/austin
>

-- 

Mike Stok <mike at stok.co.uk>
http://www.stok.co.uk/~mike/

The "`Stok' disclaimers" apply.






More information about the Austin mailing list