[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] search string




>I've put together the following search string script (below). When it 
>finds the string it prints out the whole line that the string was found 
>in. What I've been trying to do for the last 3 days is to get the results 
>written to a new variable so I can use later in my script. 


#!perl

$file = "myfile.dat";

print ("search?\n");
$search = <STDIN>;
chop ($search);

open (INFILE, $file) ||
        die ("Can't open input file!\n");
while (<INFILE>) {
        if (/$search/i) {
                chomp;          # strip off newline 
                $match = $&;    # $& contains the pattern that
                                # produced the match which put
                                # us in the if block.
                last;           # exit the while loop instead of
                                # going through to the bitter end
                                # since we've got what we want (but 
                                # see below).   
        }
}

print ("$match\n");

I think the problem with your original code was that you continued
using $line even after you'd found a match and essentially threw away
its contents after printing them once (inside the if statement).  At
the end of <INFILE>, $line got set to nothing (or maybe to the last
line, which might have been just '\n'?) and so didn't print out what
you expected when you referred to it outside of the while loop.

Above is how I'd rewrite what you sent, but you should note that it
will only find the first match.  If you remove the 'last;' statement,
it will only find the last match.  If you want to find *all* of the
matches, you might try the following:

$i = 0;
while (<INFILE>) {
        if (/$search/i) {
                chomp;
                $match[$i] = $&;
                $i++;
        }
}

foreach $result (@match) {
        print "$result\n";
}