Training, Open Source
computer languages


PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 

Search our site for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
RegEx in scalar

Posted by Akuma (Akuma), 1 August 2005
hi, everyone

I try to use replacment in PERL with the function s/$pattern1/$pattern2/gi;.
the two scalars are strings with regex pattern like :

$pattern1 = "(.*?)mysearch(.*)";
$pattern2 = "$1myreplacement$2";

When I run this script, the result is :

$1myreplacement$2

It's not what I want of course. It's the same thing this other special caracters like '\.' which is print '\.' and not '.'.

Help me please I don't know what to do.

The two pattern are read in a file.

Posted by admin (Graham Ellis), 1 August 2005
I think you have two  immediate problems in your sample code:

a) The running up of a variable name straight into a piece of text means that Perl sees it as a longer variable name.  In other words  $1myreplacement is seen as being a single name - not $1 followed by the text myreplacement.   This can be solved by writing ${1}myreplacement - curly braces can be used in Perl to limit the extent of a variable name

b) The $2 (and after item (a) has been corrected, $1 as well) are being interpretted at the time you assign to $pattern2, which is before they're set in the regular expression match.   If you set up $pattern2 to contain \1 and \2 for the backstring substitutions, then you should be able to get the results you want - but bear in mind that you'll need to code something like \\1 and \\2 in order to prevent the " operator acting on the \ character at the assignment.   You could use ' instead.

I'm worried that this sounds like a complicated answer and I think you're trying to do something very simple.    Why not just write:

$pattern1 = "Dover";
$replaceby = "Folkestone";
$ourjourney =~ s/$pattern1/$replaceby/gi;

Regular expressions look for a pattern *within* the source string, so the whole .* business at the start and end is usually un-necessary.

Note also that the replacement string (the output) is NOT a regular expression ... your use of the variable name $pattern2 in the original example was misleading.



This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.


WELL HOUSE CONSULTANTS LTD.: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 707126 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho