Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

regex - How can I implement Unix grep in Perl?

How can I implement grep of Unix in Perl? I tried to use Perl's built-in grep. Here is the code which is not working:

$pattern = @ARGV[0];
$file= @ARGV[1];

open($fp,$file);

@arr = <$fp>;

@lines = grep $pattern, @arr;

close($fp);
print @lines;

And by the way, i am trying only basic grep functionality not full featured and secondly i don't want to do string parsing myself. I want to use inbuilt grep or some function of Perl.

Thanks in advance :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As you already accepted an answer, I am writing this answer for reference for future readers searching for similar problems, but not exactly yours:

As people have answered already, the way of simulating grep with perl is to use the online approach. For the use of perl as a 'better' grep (and find and cut and...) I recomend the book minimal perl and you are lucky because the chapter for 'perl as a "better" grep' is one of the sample chapters.

Here you have more examples inspired from the book:

perl -wnle '/foo/ and print' null.txt  # normal grep
perl -wnle '/foo/ and print "$ARGV: $_"' null.txt # grep -H
perl -wnle '/foo/ and print $ARGV and close ARGV' null_1.txt null_2.txt # grep -l

In the last example ARGV is the current filehandle, and as with -l you are interested in finding files with the match you can print the file name and go for the next file after the first match in a file.

Also you can search by paragraph instead by line:

$ perl -00 -wnl -e '/BRIBE/i and print;' SenQ.testimony
I knew I'd be in trouble if
I ACCEPTED THE BRIBE!
So I did not.

My minimum bribe is $100k, and she only offered me $50k,
so to preserve my pricing power, I refused it.

Or find only the first match:

$ perl -00 -wnl -e '/BRIBE/i and close ARGV;' SenQ.testimony
I knew I would be in trouble if
I ACCEPTED THE BRIBE!
So I did not.

And finally if you ask about grep and perl, I think thay I should mention ACK. It implements, in perl, the grep functionality and extend it. This is a wonderful tool and as a plus you can have it also as a CPAN package. I have always use as a command line, I don't know if you can access its methods directly from your perl programs but this would be very nice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...