why a simple $a =~ $b doesnt work ?

A

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."
 
T

Tassilo v. Parseval

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top