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

Hello Hello Monks, Juts a quick question really. I have a search script which searches the content of files for a particular pattern the user has entered.
My question is how do I get the script to search for patterns which are not case sensitive?
#!/usr/bin/perl use warnings; use strict; print 'Enter a File name: '; chomp (my $file = <STDIN>); die "$file can't be found\n" unless -e $file; print 'Enter a search pattern: '; chomp (my $pattern = <STDIN>); open (F, '<', $file) || die $!; my @lines = <F>; my $cnt = @lines; my $found = 0; foreach my $line (@lines) { print $line and $found++ if $line =~ /\Q$pattern\E/; } print "\nTotal lines matched: $found\n";

Thanks monks!!!

Replies are listed 'Best First'.
Re: case sensitive addition
by Limbic~Region (Chancellor) on May 14, 2010 at 03:05 UTC
    Nathan_84,
    The answer to your question is to read perlre and see that the /i modifier makes the regex case insensitive. The thing is, the code has a lot more that could be improved then just the case sensitivity. For instance, you are using a bare word file handle, have a variable $cnt that you don't use and are slurping the entire file into memory.

    Cheers - L~R

        Use the following code to match the case insensitive. 
      
      if($line=~/$pattern/i) { $found++ }
        Hi thanks for the reply.
        I must be inputting the code you gave me in the wrong place. Please can you say where exactly I should insert this.
        Thanks
Re: case sensitive addition
by JavaFan (Canon) on May 14, 2010 at 09:51 UTC
    Faster to write, and less annoying for the user (doesn't have to answer questions):
    grep -c -i -F <PATTERN> <FILE>
    Code reuse doesn't stop at the Perl/non-Perl border.