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

Discussion in 'Perl Misc' started by Aristotle, Jul 17, 2004.

  1. Aristotle

    Aristotle Guest

    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."
    Aristotle, Jul 17, 2004
    #1
    1. Advertising

  2. 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$&."'!#+sexisexiixesixeseg;y~\n~~dddd;eval
    Tassilo v. Parseval, Jul 17, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Mr. SweatyFinger
    Replies:
    2
    Views:
    1,839
    Smokey Grindel
    Dec 2, 2006
  2. Janaka Perera
    Replies:
    0
    Views:
    1,123
    Janaka Perera
    Oct 29, 2007
  3. Replies:
    3
    Views:
    432
    alex23
    May 27, 2008
  4. Vince /.

    simple code doesnt work

    Vince /., Sep 20, 2006, in forum: Ruby
    Replies:
    4
    Views:
    121
    MonkeeSage
    Sep 20, 2006
  5. pd
    Replies:
    2
    Views:
    112
    ChrisHolland@InternetBrands
    Jun 1, 2007
Loading...

Share This Page