Adriano Allora am Montag, 2. Januar 2006 12.48:
> hi to all,
> a friend of mine ask me for a perl script to change regexp patterns in
> some texts (he can learn regexp, but I suppose he won't learn perl). So
> I start write this one to him.
> I have a problem:
> ==> with pattern = (dir)ectory and replacement = $1, why the script
> does not eval $1 as "dir"? how I can change the script to make it works
> as I want?
because there is no $1 at the point you test it. You get an $1 by putting '()'
in a match/substitution.
btw: What would be the purpose of evaling it?
> #!/usr/bin/perl -w
add
use strict;
here and declare your variables with my (good style).
> $^I ='_old';
> print "pattern: ";
Single quotes are sufficient here and on several places below, since nothing
is interpolated into the string.
> $pattern = <STDIN>;
> chomp($pattern);
> print "replacement: ";
> $replacement = <STDIN>;
> chomp($replacement);
> print "\n print \"s\" to confirm substitution; print \"n\" to avoid it
> print \"n\" \n\n";
The above print statements are a bit messy imho.
Maybe you also want to give out 'type' instead of 'print'.
> while(<>)
> {
> $choice = "";
> if(/$pattern/gi)
the g modifier is not necessary here, because the if branch is executed on one
or more occurences of $pattern.
> eval $replacement if $replacement eq "$1";
> print STDOUT "I'd subsitute this one => ". $_;
> $choice = <STDIN>;
> chomp($choice);
> }
> s/$pattern/$replacement/gi if $choice eq "s";
> print;
> }
The script behaves a bit strange by echoing most of the input.
You could make it more userfriendly by avoiding this and give out messages
what to do at the appropriate places.
hth, joe
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>