in reply to Help with Search String

1. use 'or' instead of '||'
2. use if ($_ =~ /Perl/ ) instead of if ($_ =~ "Perl")
3. Check file close for errors (same as open)

Cheers
Chris
PS: pls use code tags < code > < / code > (only without the spaces)

Replies are listed 'Best First'.
Re^2: Help with Search String
by btobin0 (Acolyte) on Dec 06, 2007 at 07:00 UTC
    I have done the following steps. Number 2 is where I need my help. I want to change it from
    ($_ =~ /Perl/ )
    to use a list of names in a .txt or .dat file. as the search string. Is this possible? say filename is names.txt
    Bob John Jenna Whoever
      Yes, very possible. Say that you have your names, one per line, in names.txt. You can read them into an array then use join to join the array members into a string separated by the pipe symbol ('|') which is the alternation metacharacter in a regex. Thus your pattern reads match Fred or Joe or ... or Pete. Like this.

      use strict; use warnings; my $namesFile = q{names.txt}; open my $namesFH, q{<}, $namesFile or die qq{open: $namesFile: $!\n}; my @names = <$namesFH>; close $namesFH or die qq{close: $namesFile: $!\n}; chomp @names; # Remove line terminators my $namesPatt = join q{|}, @names; my $dataFile = q{data.txt}; open my $dataFH, q{<}, $dataFile or die qq{open: $dataFile: $!\n}; while ( <$dataFH> ) { print qq{Found name $1\n} if /($namesPatt)/; } close $dataFH or die qq{close: $dataFile: $!\n};

      Note that I use parentheses in the regex to capture the name matched for later use in $1. I hope this is helpful.

      Cheers,

      JohnGG

      Update: Corrected poor punctuation/grammar.

        Now I have edited a few things and it now prints everything in the list. It print the output with the right response. but when saved it prints all 4 sentences. What am I doing wrong?
        use strict; use warnings; my $namesFile = q{names.txt}; open my $namesFH, q{<}, $namesFile or die qq{open: $namesFile: $!\n}; my @names = <$namesFH>; close $namesFH or die qq{close: $namesFile: $!\n}; chomp @names; # Remove line terminators my $namesPatt = join q{|}, @names; my $dataFile = q{data2.txt}; open my $dataFH, q{<}, $dataFile or die qq{open: $dataFile: $!\n}; while ( <$dataFH> ) { print qq{Found name $_\n} if /($namesPatt)/; open FILE, ">>/home/btobin/data3.txt" or die "Unable to Open: $!"; print FILE "$_\n"; <--- somehow this is wrong close FILE; } close $dataFH or die qq{close: $dataFile: $!\n};
        Sentences used:
        This is a data file created to learn how to use Perl . This is how Bob found his way. I wonder what Jonny is going to do. This is a test.