behd has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks & fellows,

Could anyone help me with this piece of code ?
I can't match my lines with the var :(
use DBI; use strict; my $ndata = "\\\\MYSERVER\\C\$\\Temp"; my $line; my $ndir; my $dblist = `dir $ndata /s`; my @dbline = split /\n/, $dblist; foreach $line (@dbline) { # if ($line =~ m/(??{$ndata})/) { # don't work # if ($line =~ m/$ndata/) { # don't work if ($line =~ m/\\\\MYSERVER\\C\$\\Temp/) { # works BUT I want to u +se $var !!! $ndir = $'; print "$ndir\n"; } }

Thanks in advance for any suggestion...

Replies are listed 'Best First'.
Re: pattern matching and interpolation...
by ikegami (Patriarch) on Jun 14, 2006 at 15:55 UTC
    Slashes and $ have special meaning in regexps, so you need to escape them. You've escaped them for the quotes (to tell the quotes they are not special), but you didn't also escape them for the regexp to tell the regexp they are not special. You want
    my $ndata = "\\\\MYSERVER\\C\$\\Temp"; # \\MYSERVER\C$\Temp my $quoted_ndata = quotemeta($ndata); # \\\\MYSERVER\\C\$\\Temp m/$quoted_ndata/

    or

    my $ndata = "\\\\MYSERVER\\C\$\\Temp"; # \\MYSERVER\C$\Temp m/\Q$ndata\E/

    You want to locate $ndata at the begining of $line, so you need to add ^, as follows:

    m/^\Q$ndata\E/

    Don't use $'. It will slow down every regexp in your program that doesn't have captures. Use the following instead:

    if ($line =~ m/^\Q$ndata\E(.*)/) { my $ndir = $1; print "$ndir\n"; }

    Finally, searching for a constant string using a regexp is inefficient. Use the following instead:

    if (index($line, $ndata) == 0) { my $ndir = substr($line, length($ndata)); print "$ndir\n"; }

    Updated.