Click to See Complete Forum and Search --> : pattern matching with a scalar


Gord
04-16-2005, 01:03 PM
How can I use a scalar as the full pattern matching operator string?
eg:

$story="Mary had a little lamb";
$pattern="s/Mary/Larry/";

$story=~ $pattern;

ie:
This works :
$story =~ s/Mary/Larry/;
But this does not:
$story =~ $pattern;

I'm new to CGI/Perl so any help is appreciated.

Thanks
Gord

Charles
04-16-2005, 02:13 PM
Quotes and quote like operators work a little differently in Perl. There are single quotes and then there are double quotes. Double quotes do variable substitution and take more overhead. You should use single quotes instead. And you can use any character that you want as your quote mark.

Regular expressions are quote like operators. You can't do exactly what you want but these operators also do variable substitution.

$story = 'Mary had a little Lamb';
$pattern1 = 'Mary';
$pattern2 = 'Larry';
$story =~ s/$pattern1/$pattern2/;
print $story;

or

$story = q|Mary had a little Lamb|;
$pattern1 = q|Mary|;
$pattern2 = q|Larry|;
$story =~ s|$pattern1|$pattern2|;
print $story;

or even

$story = 'Mary had a little Lamb';
$pattern1 = 'Mary';
$pattern2 = 'Larry';
$story =~ s"$pattern1"$pattern2";
print $story;

but this will not work

$story = 'Mary had a little Lamb';
$pattern1 = 'Mary';
$pattern2 = 'Larry';
$story =~ s'$pattern1'$pattern2';
print $story;

Gord
04-16-2005, 02:58 PM
Thanks for that Charles.
As I mentioned this is a learning curve for me.
I've managed to create a html form which send data to the .cgi file, which opens & reads a text file & returns a reply and new html form to the browser.
My idea was that the 'browser' user could input a pattern match expression ( s/Mary/Larry or perhaps m/Mary/g or whatever) & the script could return the result , a quick method of inputting & seeing the results of the many combinations of pattern matching operators.
From what you say, the initial 's' or 'm' of the pattern must be hard coded into the cgi script.
Hope this makes sense.
Gord

Charles
04-16-2005, 07:27 PM
I think that you might be interested in the Perl eval (http://www.perldoc.com/perl5.8.0/pod/func/eval.html) function.

Also, you should read the Perl CGI.pm (http://www.perldoc.com/perl5.8.0/lib/CGI.html) documentation if you haven't already.