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

I am practing to find keyword inside context, I tried:
#!/usr/bin/perl use strict; my $keyword = 'Three-element literal'; my $string = 'The fred array gets a Three-element literal'; if ($keyword =~ substr ($string, 0, length $keyword)){ print "it is match!\n"; }else { print "it is not match!\n"; } exit;
The result is: It is not match! Why? How can I find whether keyword is inside a string or not? Thanks!!

Replies are listed 'Best First'.
Re: match problem
by Limbic~Region (Chancellor) on Apr 27, 2003 at 21:47 UTC
    Anonymous Monk
    Or perhaps you wanted index instead of substr?:

    #!/usr/bin/perl use strict; my $keyword = 'Three-element literal'; my $string = 'The fred array gets a Three-element literal'; if ((index $string, $keyword) != -1) { print "it is match!\n"; } else { print "it is not match!\n"; }

    Cheers - L~R

    Update: PodMaster pointed out to me I shouldn't be posting when I am overtired - changed ne to !=

Re: match problem
by jasonk (Parson) on Apr 27, 2003 at 21:33 UTC

    I have no idea what that substr is trying to do, but perhaps you wanted:

    #!/usr/bin/perl use strict; my $keyword = 'Three-element literal'; my $string = 'The fred array gets a Three-element literal'; if ($string =~ /$keyword/){ print "it is match!\n"; }else { print "it is not match!\n"; }

    We're not surrounded, we're in a target-rich environment!
Re: match problem
by Cody Pendant (Prior) on Apr 27, 2003 at 21:48 UTC
    If you print out this:
    substr ($string, 0, length $keyword)
    you'll see that it's "The fred array gets a".

    It equates to "characters zero to 20 of $string"..

    So what you asked Perl to do is tell you if your keyword contained those 20 characters.

    So, yes, you were obviously a little confused.
    --

    “Every bit of code is either naturally related to the problem at hand, or else it's an accidental side effect of the fact that you happened to solve the problem using a digital computer.”
    M-J D