On Aug 20, 11:28 pm, [EMAIL PROTECTED] (Christopher Spears) wrote:
> I'm working on the second exercise of the second
> chapter.  I'm supposed to write a program that asks
> the user to type a regular expression.  The program
> then uses the regular expression to try to find a
> match in the directory that I hard coded into the
> program.  Here is what I have so far:
>
> #!/usr/bin/perl -w
> use strict;
>
> print "Enter regular expression: ";
>
> chomp(my $regexp = <STDIN>);
> #print $regexp;
>
> opendir(CPPDIR,"/home/io/chris_cpp/") or die "Could
> not open directory: $!";
> my @allfiles = readdir CPPDIR;
> closedir CPPDIR;
>
> foreach $_(@allfiles){
>         if ($_ =~ \$regexp){
>                 print $_."\n";
>         }
>
> }
>
> My problem lies with the matching part.  I'm not sure
> how to use the string that I stored in the $regexp
> variable as a regular expression.  Any hints?

Shawn and Jeff each gave you half of the answer.

Jeff pointed out that when your pattern is contained in a variable,
you should use quotemeta().  This will backslash any metacharacters
the variable might contain, so that they match themselves rather than
being "special" in the pattern match (so any periods match periods,
rather than "any character", plus signs match plus signs, rather than
meaning "one or more of the previous", etc):
$regexp = quotemeta($regexp)

And Shawn pointed out that the proper syntax for a pattern match is:
$_ =~ /$regexp/

Those two lines should be combined:
$regexp = quotemeta($regexp);
foreach $_(@allfiles){
         if ($_ =~ /$regexp/){
                 print $_."\n";
         }
}


Or, instead of calling quotemeta() explicitly, you can use the \Q and
\E escape sequences to do the backquoting within the pattern match
itself:

foreach $_ (@allfiles) {
     if ($_ =~ /\Q$regexp\E/) {
         print $_ . "\n";
     }
}


Also note that an experienced Perl programmer would either eliminate
the $_ whenever it's not needed:
foreach (@allfiles) {
   if (/\Q$regexp\E/) {
       print "$_\n";
   }
}

Or would use a better variable name as the loop iterator:
foreach my $file (@allfiles) {
    if ($file =~ /\Q$regexp\E/) {
        print "$file\n";
    }
}


Hope that helps,
Paul Lalli


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


Reply via email to