Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Simple search and output

by davido (Cardinal)
on Oct 20, 2018 at 15:51 UTC ( #1224389=note: print w/replies, xml ) Need Help??


in reply to Simple search and output

In Perl you would do something like this:

perl -lne 'print if /pattern/' filename

If you were not constrained to use Perl you would probably do this instead:

grep 'pattern' filename

Anywhere that comes with Perl pre-installed, you probably already have grep too. Anywhere that Perl does not come pre-installed, installing Perl takes longer than installing a few GNU tools (even on Windows there's that whole Ubuntu on Windows thing, plus many older solutions that provide essential shell tools).

Perl is useful for this kind of thing because it can be extended far beyond the simple semantics of GNU grep. But if your needs actually are simple, the simpler tool is grep. If this is a learning exercise, then definitely go down the Perl route. If it's just to get something done, consider grep, where you can read a single manpage and learn it all, versus a full featured programming language where perlintro is just the start.

So if you do go with Perl for this, it might come in handy to learn what it is that one-liner up above is doing, and how it works. If you were to convert that one-liner to a proper script, it should look more like this:

use strict; use warnings; while (defined(my $line = <>)) { chomp $line; if ($line =~ m/pattern/) { print "$line\n"; } }

The <> operator reads from the file presented on the commandline (found in the @ARGV array), one line at a time. If there is a line to read, the operation will have a value that makes the defined() condition true. So after there are no more lines to read, the condition becomes false and you stop looping. chomp removes the trailing newline from each line. Then you test if the line matches a pattern. If it does, you print that line out with a trailing newline.


Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1224389]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2019-08-22 02:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?