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

Hi all,
I'm more of a beginner, than an expert. My task: Compare 2 string values and see if $str1 is present in $str2, if yes then change the value of $str1 to $str2.

What I have: $str1="Mar" and $str2="Marketing" I have tried using this:

  1. if ($str1 =~ $str2) { do something; } but this returns me a false!
  2. if ($str1 le $str2) { do something; } this works but does not give me case insensitivity that is it returns a false if I try to compare if ($str1 le $str2 || $str1 eq $str2) {do something;} (where $str1 is "mar" and $str2 is "Marketing")
  3. There are some other ways that I cld try but I feel they are too dumbo ways like putting both the strings into arrays and then comparing them.
That's when I thought u guys would liek to know somethign more today :)

Any help or suggestion would be appreciated
Jeshua

Discovery

edited: Thu Jun 20 18:45:01 2002 by jeffa - added code tags and formatting

Replies are listed 'Best First'.
Re: Compare 2 string values
by kvale (Monsignor) on Jun 20, 2002 at 04:14 UTC
    To see if $str1 is in $str2, you could use the matching operator:
    $str1 = $str2 if $str2 =~ /$str1/;
    This will work for strings containing simple alphanumerics. For $str1 that might contain regex metacharacters like \,{,}, *, etc., quote the string first:
    $str1 = $str2 if $str2 =~ /\Q$str1\E/;

    -Mark
Re: Compare 2 string values
by thelenm (Vicar) on Jun 20, 2002 at 04:17 UTC
    You probably want something like this:
    $str1 = $str2 if $str2 =~ /\Q$str1\E/i;
    The \Q and \E escape special characters in $str1, if there are any. The /i modifier gives you case-insensitivity.

    -- Mike

    --
    just,my${.02}

Re: Compare 2 string values
by Zaxo (Archbishop) on Jun 20, 2002 at 04:28 UTC

    Try index. This assumes $[ is 0 as it ought to be.

    $str1 = $str2 if index( lc($str2), lc($str1)) != -1;
    You don't exactly say you want case insensitivity, but example 2 comment seems to imply you do, so I threw it in. Remove the lc() functions if you don't want it

    After Compline,
    Zaxo

Re: Compare 2 string values
by Anonymous Monk on Jun 20, 2002 at 09:45 UTC
    hey Dear Monks, Thanks for your valuable suggestions. With due respects to others cool inputs, I hv implemented the Mark and Mike inputs!
    Thanks a lot once again for your revelations! :)
    Jeshua

    -Discovery
A reply falls below the community's threshold of quality. You may see it by logging in.