Christopher Spears wrote:
> I've been reading the Intermediate Perl book and am
> trying to solve one of the exercises.  I wrote a
> script that takes input from the keyboard and uses the
> input as a regular expression to search for files in a
> directory.  If the script finds a match, the filename
> is printed out.
> 
> #!/usr/bin/perl -w
> use strict;
> 
> print "Enter a regular expression: ";
> chomp(my $pattern = <STDIN>);
> 
> my $some_dir = "./ex2";
> opendir(DIR, $some_dir) || die "Can't open $some_dir:
> $!";
> my @filenames = readdir(DIR);
> 
> foreach (@filenames) {
>         if (eval {$_ =~ /$pattern/} ) {
>            print $_ . "\n";
>         }
>         print "Continuing after error: $@" if $@;
> }
> 
> I want the program to keep asking the user for a
> pattern until an empty string is entered.  I
> remembered how to do this once, but I am returning to
> Perl after learning another language.  I need to jog
> my memory!

One way to do it:

    { # begin loop
    print "Enter a regular expression: ";
    chomp(my $pattern = <STDIN>);
    last if $pattern eq '';

    my $some_dir = './ex2';
    opendir DIR, $some_dir or die "Can't open $some_dir: $!";
    my @filenames = readdir DIR;

    foreach ( @filenames ) {
        if ( eval { $_ =~ /$pattern/ } ) {
            print "$_\n";
        }
        print "Continuing after error: $@" if $@;
    }
    redo;
}



John
-- 
use Perl;
program
fulfillment

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to