in reply to Perlwanab grep array elemetns against another array
Instead of @line having only those elements from @sfile matching each $script variable, @line is a duplicate copy of @sfile.
That's incorrect. That should read
Because @line only has those elements from @sfile that match each $script variable, @line is a duplicate copy of @sfile.
One of your patterns is apparently matching every line. Specifically, your last pattern is matching every line (since only the results of the last pattern are kept).
Here are the problems you do have:
skips every second line. I think you wantwhile (<SOURCE>) { $script = <SOURCE>;
while (my $script = <SOURCE>) {
You are only keeping the lines that match last pattern. If you want the lines matched by any pattern, change
to@line=grep( /$script/, @sfile );
push @lines, grep( /$script/, @sfile );
But that's not good enough. If two patterns can match the same line, you'll end up with duplicate lines in @line. You want something like
@line = grep( /$script[0]|$script[1]|.../, @sfile );
Why are you appending to (awfully named) newfile.txt?
Finally, you're using global variables all over the place. Start by using use strict;, and fix the errors that were previously hidden and fix the file handles too.
Solution:
#!/usr/bin/perl -w use strict; my $pat_qfn = '30.txt'; my $in_qfn = 'searchfile.txt'; my $out_qfn = 'newfile.txt'; my $pat; { open(my $pat_fh, '<', $pat_qfn) or die("Can't open pattern file $pat_qfn: $!\n"); chomp( my @pats = <$pat_fh> ); ($pat) = map qr/$_/, join '|', @pats; } open(my $in_fh, '<', $in_qfn) or die("Can't open input file $in_qfn: $!\n"); open(my $out_fh, '>', $out_qfn) or die("Can't create output file $out_qfn: $!\n"); while (<$in_fh>) { print $out_fh $_ if /$pat/; }
Of course, if you don't mind specify the input and outfile files on the command line, the program becomes much simpler and much more flexible.
#!/usr/bin/perl -w use strict; my $pat_qfn = shift(@ARGV); my $pat; { open(my $pat_fh, '<', $pat_qfn) or die("Can't open pattern file $pat_qfn: $!\n"); chomp( my @pats = <$pat_fh> ); ($pat) = map qr/$_/, join '|', @pats; } while (<>) { print if /$pat/; }
filter 30.txt searchfile.txt > newfile.txt
Update: Fixed typo in var name
|
|---|