Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

regular expression substitution

Status
Not open for further replies.

ianfo

Programmer
Aug 20, 2002
29
0
0
GB

Hi,

If I have something like

$var="abcd";

How can I make a substitution to the contents of $var and display the substituted output without making any changes to the actual contents of $var.

So in the above example, I want to keep the contents of $var the same, but in a print statement, I want to display the contents of $var but substitute the letter d for something else.

I was hoping you could do something like

print(s/d/newstring/$var);

But that doesn't work.

Any help much appreciated.
 
Try using a /[r]/; , that might work without all the other parameters.
 
I don't think the print function is going to evaluate the regex replace on-the-fly. You'll need to make at least one more step(use an intermediate var) to make the desired output happen.

Replace the d with a %.
Code:
#!perl
$var  = 'abcd';
$_ = $var;
s/d/print "$`".'%'."$'"/e;
'hope this helps

If you are new to Tek-Tips, please use descriptive titles, check the FAQs, and beware the evil typo.
 

I was hoping there would be a 1 liner that would help to keep things tidy.

Thanks for all your help...
 
This borders on obfuscation rather than tidyness but here is a one-liner:
Code:
print  +( ($tmp = $var) =~ s/d/newstring/ && "$tmp\n" );

jaa
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top