Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Perl Misc (http://www.velocityreviews.com/forums/f67-perl-misc.html)
-   -   why a simple $a =~ $b doesnt work ? (http://www.velocityreviews.com/forums/t887303-why-a-simple-a-b-doesnt-work.html)

Aristotle 07-17-2004 04:33 AM

why a simple $a =~ $b doesnt work ?
 
I'm trying a simple 'if ($a =~ $b)' function, but it doesnt seem to
work, when clearly $b is contained in $a. Is there any particular
reason why a =~ expression wouldnt work correctly ?

ie trying to match ". Palms and soles, of: (2)" in ". Palms and soles,
of: (2) HYPER. LED."

Tassilo v. Parseval 07-17-2004 05:28 AM

Re: why a simple $a =~ $b doesnt work ?
 
Also sprach Aristotle:

> I'm trying a simple 'if ($a =~ $b)' function, but it doesnt seem to
> work, when clearly $b is contained in $a. Is there any particular
> reason why a =~ expression wouldnt work correctly ?
>
> ie trying to match ". Palms and soles, of: (2)" in ". Palms and soles,
> of: (2) HYPER. LED."


If all you want to do is checking whether one string is contained in the
other, you'd be better off using index():

if (index($a, $b) != -1) {
...
}

The reason why your regex approach doesn't work as you expect is that
your string $b contains characters with a special meaning in regex-ish
context, most notably '.', '(' and ')'. This becomes more obvious when
you use the content of $b literally as a pattern:

". Palms and soles, of: (2) HYPER. LED." =~ /. Palms and soles, of: (2)/;
^ ^ ^

The special characters are marked. The pattern matches strings which

- begin with any character (excluding newline)
- followed by the string ' Palms and soles, of: '
- followed by '2' which is captured in $1

You can tell perl to take the pattern as a literal string without paying
attention to any regex meta-characters:

$a =~ /\Q$b/;

The \Q assertion treats anything that follows (up to an optional \E end
marker) literally.

Tassilo
--
$_=q#",}])!JAPH!qq(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus})(rekcah{lrePbus})(lreP{rehtonabus}) !JAPH!qq(rehtona{tsuJbus#;
$_=reverse,s+(?<=sub).+q#q!'"qq.\t$&."'!#+sexisexi ixesixeseg;y~\n~~dddd;eval


All times are GMT. The time now is 07:16 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.