[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Beginner's question



On Sat, Feb 05, 2000 at 09:11:34AM -0500, Jeff Myers wrote:
> This works fine but there HAS to be a better way...
> 
> open (WORDSLIST,"WORD LIST for Perl a") || die "can't open wordlist:$!";
> 
> while ( defined ( $tester = <WORDSLIST>)) {
> chomp ($tester);
> if ($tester =~  /^lie..$/ ) { print "$tester\n"; };
> }
> close (WORDSLIST);
> print "all done\n";
> 

I would suggest something like this:

#!perl

my $wordlist = "WORD LIST for Perl a";
open (WORDLIST, $wordlist) or die "Can't open $wordlist: $!\n";

while (1) {
    print "> ";
    chomp($re = <>);

    last unless defined $re and length $re;

    eval "while (<WORDLIST>) { print if /$re/o }";

    if ($@) {
        warn "$@\n";
    }

    seek(WORDLIST, 0, 0) or die "Can't seek in $wordlist: $!\n";
}

__END__


Prompt for the regular expression.  Exit on EOF or a blank line.
eval a while loop that prints out matching words.  If there was an error in
the eval, notify the user.  Seek to the beginning of the word list, and
start over.

Using eval allows you to trap errors caused by the user entering an
improper regex.  Then, it's more efficient to put the loop inside the eval,
rather than the eval in inside the loop; otherwise you'd be compiling the
string for every word in the file.  Since the regex is constant within
the scope of one execution of the eval, you can use /o for efficiency.

Note that this script ignores security concerns for the user's input.
Don't do anything foolish with it.

Ronald

# ===== Want to unsubscribe from this list?
# ===== Send mail with body "unsubscribe" to macperl-request@macperl.org