[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 ($line = <INFILE>) {
>         if ($line =~ /$search/i) { print ("$line\n"); }
> }
> print ("$line");

I would recommend something like the following. It puts each match into an
element of an associative array. This way you can preserve the line number
as well as the text string of the line:

#!perl
$file = "myfile.dat";
print ("search?\n");
$search = <STDIN>;
chop ($search);
$line_number=1;
open (INFILE, $file) || die ("Can't open input file!\n");
while (<INFILE>) {
   chop $_;
   if ($_ =~ /$search/i) {
      $found{$line_number} = $_;
      print ("line $line_number:\n$_\n"); }
   }
   $line_number++;
}

$num_matches=keys(%found);
print "$num_matches matches found:\n";
foreach $key (keys %found) {
   print "line $key:\n$found{$key}\n";
}

# end of script

-Dave