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

Hi Gurus, I have a program which searches a for a string in within a target string and prints yes or no if the string is present or not. The following is how code looks like
$mytarget = "I am a perl program"; $mystring = "Perl"; if ($mytarget =~ m/$mystring/i) { print "It matches\n"; } else { print "It doesn't match\n"; }

This prints "It matches" though the case does not match as I am using regex m//i . Now how can I actually fetch the actual string "perl" from $mytarget and print on the screen,

"The actual string in the target is : perl". Thanks in advance

Replies are listed 'Best First'.
Re: Regex: Extracting the case insensitive string and printing on the output
by Ratazong (Monsignor) on Nov 28, 2011 at 10:10 UTC
      Thanks Ratazong. Made that simple. :)
Re: Regex: Extracting the case insensitive string and printing on the output
by trizen (Hermit) on Nov 29, 2011 at 00:54 UTC
    I recommend to use ${^MATCH}. It is much faster than capturing to $1
    Benchmark: timing 2222234 iterations of code_1, code_2... code_1: 4 wallclock secs ( 4.03 usr + 0.00 sys = 4.03 CPU) @ 55 +1422.83/s (n=2222234) code_2: 2 wallclock secs ( 2.27 usr + -0.01 sys = 2.26 CPU) @ 98 +3289.38/s (n=2222234) Rate code_1 code_2 code_1 551423/s -- -44% code_2 983289/s 78% --

    ... and don't forget about quotemeta or \Q \E when matching $strings.
    $mytarget = "I am a perl program"; $mystring = "Perl"; if ($mytarget =~ m/\Q$mystring\E/i) { print "It matches: ${^MATCH}\n"; } else { print "It doesn't match\n"; }
      I recommend to use ${^MATCH}.

      Always use the /p regex modifier when using  ${^MATCH} and friends. The use of  ${^MATCH} may appear to work without the /p modifier, but this is only fortuitous.

      Quoth perlvar (emphasis added):

      ${^MATCH}
      This is similar to $& ($MATCH) except that it does not incur the performance penalty associated with that variable, and is only guaranteed to return a defined value when the pattern was compiled or executed with the "/p" modifier.
Re: Regex: Extracting the case insensitive string and printing on the output
by ansh batra (Friar) on Nov 28, 2011 at 10:08 UTC
    i is for ignore case
    remove i and then run
    Edit:
    $& can be used to get the matched pattern