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

Hi monks, I'm new to perl programming, I'm trying to write a small program that opens a text file with some phrases and then try to match it with another string. The problem is that it never matches. Why? I know that this code can be optimized, any suggestion is welcome.
open $FILE , "<", "db.txt" or print "Unable to open file"; @idstring = <$FILE>; $count = 0; while ($idstring[$count]) { $string = $idstring[$count]; if ($msg =~ m/.*$string.*/i) { print "$idstring[$count] found"; } $count++; } close $FILE;

Replies are listed 'Best First'.
Re: Matching a scalar variable
by jethro (Monsignor) on Jul 31, 2009 at 17:56 UTC

    It probably finds nothing because there is a \n at the end of each line you read from a text file. Adding chomp(@idstring); or chomp $string; will take care of that

    Also if $string has regex special characters in it, the result will be quite different from what you expect. Use \Q and \E to escape the special characters

    I would suggest using foreach instead of while. Looks much cleaner that way and you don't need a $count variable:

    foreach $string (@idstring) { chomp($string); if ($msg =~ m/.*\Q$string\E.*/i) { print "$string found"; last; } }

    Update: Removed reference to $count in my loop, thanks to ssandv for spotting it

Re: Matching a scalar variable
by jwkrahn (Abbot) on Jul 31, 2009 at 18:21 UTC

    You probably want something more like this:

    open my $FILE , "<", "db.txt" or print "Unable to open 'db.txt' $!"; while ( my $string = <$FILE> ) { if ( $msg =~ /$string/i ) { print "$string found\n"; } } close $FILE;
Re: Matching a scalar variable
by alexm (Chaplain) on Jul 31, 2009 at 21:30 UTC

    Aside from the other comments by fellow monks, you may need to perform the match the other way around ($string =~ m/$msg/i). It mostly depends on what you want to achieve.

Re: Matching a scalar variable
by Anonymous Monk on Jul 31, 2009 at 17:45 UTC
    perldoc -f index
    if ( -1 != index lc $msg, lc $lidstring[$count] ){ print "$msg found\n"; }