Harry Putnam wrote:
>
> I posted here a while back about how to set the parameters of an
> s/// type of action, inside a script from the cmdline.
>
> Paul posted a simple script in answer that does exactly that.
> and even allows any modifier to be set from cmdline.
> (Slightly modified for clarity)
>
> cat example1.pl
> #!/usr/bin/perl -wp
> BEGIN { our($regex,$repl,$mod) = (shift,shift,shift||'') }
> eval "s/$regex/$repl/$mod";
>
> Results:
> echo something|./example1.pl '(some)(.*$)' '$1one'
> someone
>
> Paul explained in brief how and why this works but I'm having trouble
> integrating this into a more complex script, can't seem to find the
> error of my attempts.
>
> The script is awfully contrived but the idea is to get this to work
> in a script employing Getopts::Std or other complications.
>
> In the example below the input is expected to come from files so I
> dropped the -p part.
>
> In this contrived case the input file contains only the one line
>
> something
>
> I know my script is wrong but have tried a number of variations. All
> failed. Its apparent I'm lacking some basic knowledge about eval here.
>
> With a command line like:
> ./example2.pl -s '(some)(.*$)' '$1one'
^^^^^
That won't work because it be interpreted as the variable $1one instead
of the variable $1 followed by the string 'one'. You need to put parens
around the variable name like this:
./example2.pl -s '(some)(.*$)' '${1}one'
> cat example2.pl
>
> #!/usr/local/bin/perl -w
>
> $file = "./input";
>
> use vars qw($opt_s);
> use Getopt::Std;
> my $optstr ="s:";
> getopts($optstr);
>
> if ($opt_s) {
> $regex = $opt_s;
> BEGIN {
> our ($repl,$mod) = (shift,shift||'')
> }
You are not using either the -p or -n switch so you don't need this in a
begin block.
> }
>
> open(FILE,"<$file") or die;
You should include the $! variable in the error message so you know WHY
it failed.
> # NOW how to use eval here
> while(<FILE>){
> chomp;
> # how can I make these variables be seen as a legitimate piece
> # of perl code? And print the result
> # eval $_ =~ s/$regex/$repl/$mod;
> # print...
> }
Your substitution operator will work like this:
s/(?$mod:$regex)/qq("$repl")/ee;
print;
The /ee does the eval but just on the replacement half, not the whole
expression.
John
--
use Perl;
program
fulfillment
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]