Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi All,

I am trying to do the following. I have 2 variables
eg. $line='123: ABC/1.0/VAL [111:222:333:444]';
and $cont='ABC/1.0/VAL [111:222:333:444]';
And I have written the following in order to merely identify that the contents of $cont are contained with the contents of $line

if ($head=~/$cont/) { print "We have a match\n"; } else { print "No match\n"; }
But I keep getting a no match message and can't understand why. I'd really appreciate a response asap as this is seriously holding my work up
Thanx in advance,
Val

update (broquaint): added <code> tags and formatting

Replies are listed 'Best First'.
Re: Find a string within a string
by mce (Curate) on Nov 13, 2002 at 12:37 UTC
    Hi,

    Just a quick note:
    add the line

    use re debug;
    at the beginning of your script, and it all becomes clear. This will put extra debug information on you regexes, and in your case will show what to match to wich string. This is fairly readable.
    ---------------------------
    Dr. Mark Ceulemans
    Senior Consultant
    IT Masters, Belgium
Re: Find a string within a string
by Chady (Priest) on Nov 13, 2002 at 11:51 UTC

    you are getting "no match" because you are matching against another variable if ($head=~/$cont/) which should be if ($line =~ /$cont/).


    He who asks will be a fool for five minutes, but he who doesn't ask will remain a fool for life.

    Chady | http://chady.net/
Re: Correction to 1st -Find a string within a string
by Anonymous Monk on Nov 13, 2002 at 12:02 UTC
    Apologies all, error in the code I submitted in initial message The code should read
    $line='123: ABC/1.0/VAL 111:222:333:444'; $cont='ABC/1.0/VAL 111:222:333:444'; if ($line=~/$cont/) { print "We have a match\n"; } else { print "No match\n"; }
    Thanx, Val
      That code returns "We have a match". Although I'm think you hould use \Q and \E in comparison to avoid troubles with other strings.
      So the code should look like this:
      $line='123: ABC/1.0/VAL 111:222:333:444'; $cont='ABC/1.0/VAL 111:222:333:444'; if ($line=~/\Q$cont\E/) { print "We have a match\n"; } else { print "No match\n"; }
      Try it using quotemata:
      $cont='\QABC/1.0/VAL 111:222:333:444\E';
      since you're looking for the literal string.

      rdfield

[TIMTOWTDI] Re: Find a string within a string
by Zaxo (Archbishop) on Nov 13, 2002 at 20:59 UTC

    Since you want an exact match, you can call index instead, and not have to worry about regex metacharacters:

    if ( index( $line, $cont) != -1) { print "We have a match\n"; } else { print "No match\n"; }

    After Compline,
    Zaxo