On Thursday 23 March 2006 15:51, 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!
>
> "I'm the last person to pretend that I'm a radio.  I'd rather go out and be
> a color television set." -David Bowie
>
> "Who dares wins"
> -British military motto
>
> "I generally know what I'm doing."
> -Buster Keaton

Here is one way to do it.

#!/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);

#wrap your foreach around a loop
#continue loop until you find a blank line
 until ($pattern =~ /^\s*$/) {
        foreach (@filenames) {
                 if (eval {$_ =~ /$pattern/} ) {
                        print $_ . "\n";
                }
                print "Continuing after error: $@" if $@;
        }
        print "Enter a regular expression: ";
        chomp($pattern = <STDIN>);
 }

-- 
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