[Israel.pm] Doing it the perlish way

Yuval Kogman nothingmuch at woobling.org
Thu Jun 8 11:29:39 PDT 2006


On Thu, Jun 08, 2006 at 21:06:15 +0300, Yossi.Itzkovich at ecitele.com wrote:
> Hi,
> 
> I have this simple script, that acts as interactive grep on /usr/dict/words file.  Is there more "perlish" way to write it ?
> 

If I had written it it'd probably look like this:

#!/usr/local/bin/perl

# i removed -w and use these instead:

use strict;
use warnings;

my $dict = "/usr/dict/words"; # might want to make this an option
# i prefer 3-argument open and lexical file handles
open my $dict_fh, "<", $dict or die "can't open($dict): $!"; # tell them why we can't open it

my @dict = <$dict_fh>;
chomp for @dict; # trim the newlines

close $dict_fh; # it's nice to close once we're done, when you read
# the code you know it won't be used afterwords so things are
# clearer

$\ = "\n";
$, = ", ";

while (<>) { # if it's not <STDIN> we allow patterns from files too
    chomp;
	my $pat = qr/$_/; # qr is both faster and more informative
    print STDERR "pat=$pat"; # go to STDERR so that it doesn't wind up in pipes
    print grep /$pat/, @dict; # $, and $\ play a nice part here
}

-- 
  Yuval Kogman <nothingmuch at woobling.org>
http://nothingmuch.woobling.org  0xEBD27418

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 191 bytes
Desc: not available
Url : http://perl.org.il/pipermail/perl/attachments/20060608/ac52a65a/attachment.pgp 


More information about the Perl mailing list