473,626 Members | 3,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on regex substitution using variables...

Ian
Hi,

Hopefully a simple question but my brain is hurting...

I want to make a regex substitution, using search and replace
patterns contained in variables. What I want to do is:

$f = "fred.abc";
$f =~ s/(.*)\.abc/$1.def/;
print "$f\n";

but where the two parts of the substitution are variables:

my $to_pattern = "(.*)\\.abc ";
my $from_pattern = "\$1.def";
$f =~ s/$to_pattern/$from_pattern/;
print "$f\n";

Unfortunately this doesn't seem to work, where the first example
correctly prints out "fred.def" the second one doesn't seem to
do the back-substitution, and just prints "$1.def".

Is this possible, and if so, what quoting magic do I need to make
it work???

TIA,
Ian.

#!/usr/bin/perl -w

use strict;

my $f;

$f = "fred.abc";
$f =~ s/(.*)\.abc/$1.def/;

print "$f\n"; # prints "fred.def" (correct)
$f = "joe.abc";

my $to_pattern = "(.*)\\.abc ";
my $from_pattern = "\$1.def";

$f =~ s/$to_pattern/$from_pattern/;

print "$f\n"; # prints "$1.def"

# end
--
Ian

"Tamahome!! !" - "Miaka!!!"
Feb 2 '06 #1
4 12072
On Thu, 02 Feb 2006 17:06:09 +0000, Ian wrote:
but where the two parts of the substitution are variables:

my $to_pattern = "(.*)\\.abc ";
my $from_pattern = "\$1.def";
$f =~ s/$to_pattern/$from_pattern/;
print "$f\n";

Unfortunately this doesn't seem to work, where the first example correctly
prints out "fred.def" the second one doesn't seem to do the
back-substitution, and just prints "$1.def".
That is because the second part of the s/// construct is an ordinary
double quoted string. Once you have put a literal $ into a string, it is
not re-interpreted whenever the string is substituted. (What would you
expect

my $a = "X"; my $b = "\$a"; print "$b"

to print?)
Is this possible, and if so, what quoting magic do I need to make it
work???


You need, in some sence, less quoting. One way is to re-write the
substitution as a little code block (in a string) and have it evaluated:

my $from_pattern = "\$1.'.def' ";
$f =~ s/$to_pattern/eval($from_patt ern)/e;

This being Perl, I await news of the 1867 other ways to do it... :-)

--
Ben.

Feb 2 '06 #2
Ian
On 2006-02-02, Ben Bacarisse <be********@bsb .me.uk> wrote:

[snip - understood]
You need, in some sence, less quoting. One way is to re-write the
substitution as a little code block (in a string) and have it evaluated:

my $from_pattern = "\$1.'.def' ";
$f =~ s/$to_pattern/eval($from_patt ern)/e;
Ta, this gives the effect I'm after. I was contemplating doing the whole
thing in an eval() but this is neater.
This being Perl, I await news of the 1867 other ways to do it... :-)


At least!

--
Ian

"Tamahome!! !" - "Miaka!!!"
Feb 2 '06 #3
In article <pa************ *************** *@bsb.me.uk>, Ben Bacarisse
<be********@bsb .me.uk> wrote:
On Thu, 02 Feb 2006 17:06:09 +0000, Ian wrote:
but where the two parts of the substitution are variables:

my $to_pattern = "(.*)\\.abc ";
my $from_pattern = "\$1.def";
$f =~ s/$to_pattern/$from_pattern/;
print "$f\n";

Unfortunately this doesn't seem to work, where the first example correctly
prints out "fred.def" the second one doesn't seem to do the
back-substitution, and just prints "$1.def".
.... You need, in some sence, less quoting. One way is to re-write the
substitution as a little code block (in a string) and have it evaluated:

my $from_pattern = "\$1.'.def' ";
$f =~ s/$to_pattern/eval($from_patt ern)/e;
A second e modifier will force a second round of evaluation:

$f =~ s/$to_pattern/$from_pattern/ee;

This being Perl, I await news of the 1867 other ways to do it... :-)


(1866 to go :)

FYI: this newsgroup is defunct. Try comp.lang.perl. misc in the future.

Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com
Feb 2 '06 #4
On Thu, 02 Feb 2006 12:26:21 -0800, Jim Gibson wrote:
In article <pa************ *************** *@bsb.me.uk>, Ben Bacarisse
<be********@bsb .me.uk> wrote:
On Thu, 02 Feb 2006 17:06:09 +0000, Ian wrote:
> but where the two parts of the substitution are variables:
>
> my $to_pattern = "(.*)\\.abc ";
> my $from_pattern = "\$1.def";
> $f =~ s/$to_pattern/$from_pattern/;
> print "$f\n";
>
> Unfortunately this doesn't seem to work, where the first example
> correctly prints out "fred.def" the second one doesn't seem to do the
> back-substitution, and just prints "$1.def". ...
You need, in some sence, less quoting. One way is to re-write the
substitution as a little code block (in a string) and have it evaluated:

my $from_pattern = "\$1.'.def' ";
$f =~ s/$to_pattern/eval($from_patt ern)/e;
A second e modifier will force a second round of evaluation:

$f =~ s/$to_pattern/$from_pattern/ee;


Lovely! I did not know that.
This being Perl, I await news of the 1867 other ways to do it... :-)


(1866 to go :)


No, that's the one as far as I'm concerned!
FYI: this newsgroup is defunct. Try comp.lang.perl. misc in the future.


Thanks for the heads up.

--
Ben.

Feb 2 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
1876
by: Reinhold Birkenfeld | last post by:
Hello, I recently ported a simple utility script to analyze a data file from Perl to Python that uses regex substitutions, not more complex than re1 = re.compile(r"\s*<.*>\s*") re2 = re.compile(r".*\((.*)\).*") re3 = re.compile(r'^"(.*)"$') When run without these regex substitutions, the scripts' speed is nearly
0
1776
by: Justin | last post by:
Hi, First off, I must apologise for cross posting. I am having difficulty creating a pdf document using perl cgi to do substitution for multiline pdf form fields. I created a pdf template/file with substitution variables. The file is then read and variables substituted using pattern matching. When I view the pdf multiline form field using acrobat, the field seems to be truncated. Upon view the properties of the multiline text field, I...
8
1977
by: Just Me | last post by:
I want to use regular expressions to search a string, give the user the option of replacing, and then maybe replacing the data - using reg expressions for the search and the replace strings. However all the Regex replace methods seem to combine in one call the search and replace. Is there a way of doing what I want?
9
1341
by: | last post by:
I tried Dim s As String = "1 2 3 4 5" Regex.Replace(s, "3", "6") but no luck, nothing was changed?
5
5089
by: Chris | last post by:
How Do I use the following auto-generated code from The Regulator? '------------------------------------------------------------------------------ ' <autogenerated> ' This code was generated by a tool. ' Runtime Version: 1.1.4322.2032 ' ' Changes to this file may cause incorrect behavior and will be lost if ' the code is regenerated. ' </autogenerated>
7
6627
by: MtiPaulo | last post by:
I know FoxPro has excellent macro substitution but I am trying to find through MS Access. Wondering if MS Access has Macro Substitution? I will give you my basic example. In FoxPro Language Code For i = 1 to 5 strCmd = "Client" + Alltrim(Str(i)) + "=" + Alltrim(Str(i)) &strCmd && Client1 = 1 Next
11
3094
by: Steve | last post by:
Hi All, I'm having a tough time converting the following regex.compile patterns into the new re.compile format. There is also a differences in the regsub.sub() vs. re.sub() Could anyone lend a hand? import regsub
15
50214
by: morleyc | last post by:
Hi, i would like to remove a number of characters from my string (\t \r \n which are throughout the string), i know regex can do this but i have no idea how. Any pointers much appreciated. Chris
0
1144
by: Chris O | last post by:
"Larry Lowe" <llowejr@usa.netwrote in message news:ad17577.0308140714.1b14d778@posting.google.com... Hi Larry. Some responses aren't very helpful. I'll try to do a little better. The first point to note is that each Oracle instance requires a reasonable amount of system resouces as usually a considerable amount of memory is allocated to the instance and on UNIX there is typically half a dozen background processes hanging around just...
0
8269
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8711
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8642
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8512
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7203
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5576
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2630
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1515
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.