[VPM] regular-expressions and variables

Ken Clarke kencl at shaw.ca
Mon Nov 13 04:09:55 PST 2006


Just keep in mind that the contents of $variable are interpreted as a regex 
pattern.  If all you want to do is match exact character sequences, quote 
the variable IE s/^\Q$variable\E//;  $variable can contain any valid regex 
pattern.

You'll take a slight performance hit, since perl will recompile the pattern 
every time it is used unless you use the /o (only compile pattern once) 
modifier, as it has no way of knowing if the contents have changed or not. 
What I usually do if I'm going to use a pattern multiple times within a 
loop, and I know that the block containing the loop may be called multiple 
times with different patterns, is compile the pattern then use the compiled 
pattern within the loop itself.

EG

sub check_list_for_pattern {
    my ($pattern, $list_ref) = @_;
    my $compiled_pattern = qr/$pattern/;
    for (@{$list_ref}) {
        if (/$compiled_pattern/) {
            # handle match found
        } else {
            # handle no match
        }
    }

hth

>> Ken Clarke
>> Contract Web Programmer / E-commerce Technologist
>> www.PerlProgrammer.net

----- Original Message ----- 
From: "Jer A" <jeremygwa at hotmail.com>
To: <victoria-pm at pm.org>
Sent: Saturday, November 11, 2006 8:38 AM
Subject: [VPM] regular-expressions and variables


> hello all perl gurus,
>
> I have another problem - a regular expression problem
>
> how do i use scalar variables in substitution and complex matching?
>
> eg I want the following to work.
>
> $string =~ s/^$variable//;
>
> $string =~ m/^([^$variable]*)/;
>
>
> thanks in advance for your help.
>
> -Jeremy A.
>
> _________________________________________________________________
> Say hello to the next generation of Search. Live Search - try it now.
> http://www.live.com/?mkt=en-ca
>
>


--------------------------------------------------------------------------------


> _______________________________________________
> Victoria-pm mailing list
> Victoria-pm at pm.org
> http://mail.pm.org/mailman/listinfo/victoria-pm
> 



More information about the Victoria-pm mailing list