Old 28-01-2008, 05:30 PM
  post #1
mmmaung
အရြယ္ေရာက္သူ
 
အသင္း၀င္ေန႔စြဲ: Nov 2007
တည္ေနရာ: korea
ေရးသားခ်က္မ်ား: 168
ေက်းဇူးတင္စကား: 0
ပို႔စ္ 28 ခုအတြက္ 73 ဦးမွ ေက်းဇူးတင္ေၾကာင္းေျပာပါသည္။
mmmaung is on a distinguished road
Using Variables In Perl Regular Expressions

I am assuming from now on that you are familiar with substitution operator in perl: s///. A basic example:
Code:
$str =~ s/apple/orange/;
would replace the word "apple" with the word "orange". The separator "/" we used in this example can be replaced with any other non alpha-numeric character. The catch is; you have to escape the separator character inside your regular expression. So it is a better idea to use a less common character as a separator than "/". I prefer using "!" as a separator, because it is less common in strings and visually it is a good separator. So same regular expression could be written as:
Code:
$str =~ s!apple!orange!;
A common mistake people do when using regular expressions is to try to match a variable in your regular expressions.
Code:
$data =~ s!$url!http://go4expert.com!;
This is going to work properly most of the time. But sometime it won't behave as expected or you will be experiencing occasional run time errors. For example, if your $url is equal to
Code:
http://yahoo.com/do.cgi?action=go++&tell=perl
the substitution operator is going to fail and exit with an error message.
Code:
"/http://yahoo.com/do.cgi?action=go++&tell=perl/: nested *?+ in regex..."
The reason for the failure is that you can't use "++" inside your regular expression. You have to escape them. The variable might include several special variables, which have to be escaped properly. To correct way to implement this substitution is:
Code:
$temp = quotemeta($url);
   $data =~ s!$temp!http://yahoo.com!;
quotemeta() is a standard perl function and it escapes all non-alphanumeric characters in your variable.

ဘ၀ကို ေပါ့ေပါ့ေလး နဲ႕ ပါးပါးေလး ၿဖတ္ခ်င္တယ္:23::23::11:

Last edited by mmmaung; 28-01-2008 at 05:32 PM..
mmmaung is offline   Reply With Quote
Reply

တန္ဆာပလာမ်ား
ေဖာ္ျပမႈပံုစံ

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

ဖိုရမ္ေတြ ေက်ာ္ေရာက္ခ်င္ရင္ !

အျခားဆင္တူေဆြးေႏြးခ်က္မ်ား
ေဆြးေႏြးခ်က္ စတင္ေရးသားသူ ကြပ္ပ်စ္၀ိုင္း ျပန္စာမ်ား ေနာက္ဆံုးပို႔စ္
Perl and XML kothu E-books မ်ား 1 04-10-2013 11:06 AM
APress Pro Perl Parsing mmmaung E-books မ်ား 2 22-06-2008 12:08 PM
Perl Testing : A Developers Notebook mmmaung E-books မ်ား 0 28-01-2008 06:25 PM
Mastering Perl mmmaung E-books မ်ား 0 28-01-2008 05:25 PM
Mastering Regular Expressions, 2nd Edition - O?Reilly Zeiya E-Books & Tutorials 0 26-03-2007 12:08 AM


ဖိုရမ္၏ ပင္မအခ်ိန္သည္ ဂရင္းနစ္စံေတာ္ခ်ိန္ +6.5 ျဖစ္သည္။ေဒသစံေတာ္ခ်ိန္ 01:44 AM
Inactive Reminders By Icora Web Design