CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Substitution of % variables

 



rnerlikar
New User

Mar 30, 2004, 2:37 AM

Post #1 of 7 (504 views)
Substitution of % variables Can't Post

How do I substitute the following string ,

This %1 file does not exist at %2,%3

to get

This [%1] file does not exist at [%2],[%3].

s/%[0-9]/[%[0-9]]/g; gives me bizzare results.


davorg
Thaumaturge / Moderator

Mar 30, 2004, 3:21 AM

Post #2 of 7 (502 views)
Re: [rnerlikar] Substitution of % variables [In reply to] Can't Post

You need to use capturing parentheses in the regex and the captured text in the replacement string.

Code
#!/usr/bin/perl 

use strict;
use warnings;

$_ = 'This %1 file does not exist at %2,%3';

s/(%\d)/[$1]/g;

print "$_\n";


--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


rnerlikar
New User

Mar 30, 2004, 3:26 AM

Post #3 of 7 (499 views)
Re: [davorg] Substitution of % variables [In reply to] Can't Post


In Reply To
You need to use capturing parentheses in the regex and the captured text in the replacement string.

Code
 #!/usr/bin/perl  

use strict;
use warnings;

$_ = 'This %1 file does not exist at %2,%3';

s/(%\d)/[$1]/g;

print "$_\n";


Thanks it works like magic.


davorg
Thaumaturge / Moderator

Mar 30, 2004, 3:39 AM

Post #4 of 7 (497 views)
Re: [rnerlikar] Substitution of % variables [In reply to] Can't Post

No. It works like logic. There's a difference :)

--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


rnerlikar
New User

Apr 5, 2004, 2:00 AM

Post #5 of 7 (478 views)
Re: [davorg] Substitution of % variables [In reply to] Can't Post

Hi Dave,

How to make it work in the following scenario,
%11 to [%11] and also %1 to [%1] and also %s to [%s]


davorg
Thaumaturge / Moderator

Apr 5, 2004, 2:14 AM

Post #6 of 7 (477 views)
Re: [rnerlikar] Substitution of % variables [In reply to] Can't Post

What have you tried? What problems did you have?

I don't want to just hand you the answer, but I'm happy to help you work it out.

--
Dave Cross, Perl Hacker, Trainer and Writer
http://www.dave.org.uk/
Get more help at Perl Monks


rnerlikar
New User

Apr 5, 2004, 3:04 AM

Post #7 of 7 (474 views)
Re: [davorg] Substitution of % variables [In reply to] Can't Post

Sly It was way too simple..I should have got it before..I kept on trying stuff like
s/(%\d\d+)/[$1]/g; and
s/(%\d||%\d\d)/[$1]/g;
But then suddenly I realised it would be simple by doing it like this,
s/(%\w+)/[$1]/g;
Thanks for not handing out the answer straight away.
Regards

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives