Paolo Gianrossi wrote:
On Mon, 2008-09-01 at 04:42 -0700, John W. Krahn wrote:
Paolo Gianrossi wrote:
However what i want to do is subtly different: i'd like to do this:
my $rexp="m/match/g";
$text=~$rexp;
The only way to use the /g option like that is to use eval:
my $rexp = 'match';
eval { $text =~ /$rexp/g };
or even
my $rexp="s/match/subst/g";
$text=~$rexp;
Same here with the /g option:
my $rexp = 'match';
my $replace = 'subst';
eval { $text =~ s/$rexp/$replace/g };
First of all thank you (and all the others ;) for answering
This looks more hairy than I think it should...
Since I think I omitted some constraints I have, let me try to explain
my issue a tiny bit better.
What I would like to do is the following. I have a text file which I
slurp. Its contents are in $content.
Now I want to ask the user for a regex (any regex) and highlight where
(if) it matches.
If I try to hard cable the whole thing, it works just fine:
use strict;
use warnings;
use diagnostics;
my $text="this is a random text. Please match random string.\nAnother
random something.\n";
while ($text =~ s/random/final/){ #here it is hard-coded
my $l=length($`);
print substr($text, 0, $l);
print ">";
print substr($text, $l);
}
This behaviour is just what I want. Only, I'd like to ask for the regexp
to the user:
use strict;
use warnings;
use diagnostics;
my $text="this is a random text. Please match random string.\nAnother
random something.\n";
my $rexp=<STDIN>;
while ($text =~ $rexp){ #here it isn't hardcoded anymore.
my $l=length($`);
print substr($text, 0, $l);
print ">";
print substr($text, $l);
}
Of course this works not.
Also, though,
...
while (eval{$text =~ $rexp}){ # try to evaluate this, but not in the
# proper way
my $l=length($`);
print substr($text, 0, $l);
print ">";
print substr($text, $l);
}
doesn't work. eval{$text =~ $rexp} is always undef. Now, this puzzles
me, but whatever. My major point is that perldoc perlvar tells me that
$` and friends are dynamically local to the eval block, so I am no game.
Any clue about how to solve this?
Perhaps you want something like this:
$ perl -e'
my $text = "this is a random text. Please match random string.\nAnother
random something.\n";
print $text;
my $rexp = "random";
my $replace = ">final";
while ( $text =~ /$rexp/g ) {
substr $text, $-[0], $+[0] - $-[0], $replace;
}
print $text;
'
this is a random text. Please match random string.
Another random something.
this is a >final text. Please match >final string.
Another >final something.
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/