P0w3rK!d has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to perform a short directory listing "dir /b" in order to put the results into an array of files to be processed later on.
my $cmd = "dir /b $dir\\*.bat"; print "cmd = $cmd\n"; my $ret = `$cmd`;

Here is the error message:

cmd = dir /b C:\Dir\To\Scan\*.bat dir: /b: No such file or directory dir: C:DirToScan*.bat: No such file or directory

What am I doing wrong here?

Note: I already tried this... my $cmd = "dir \/b $dir\\*.bat";

Replies are listed 'Best First'.
Re: short dir listing
by runrig (Abbot) on Oct 23, 2002 at 18:02 UTC
    Another option is to use readdir:
    chdir $dir or die "Can't cd to $dir: $!"; opendir DIR, $dir or die "Can't read $dir: $!"; my @files = map { "$dir\\$_" } grep { /\.bat$/ } readdir DIR; closedir DIR;
      Thank you. :)
Re: short dir listing
by tadman (Prior) on Oct 23, 2002 at 18:21 UTC
    It might be a lot easier to use File::Find:
    use File::Find; my @found; find({ wanted => sub { if (/\.bat$/i) # Catches 'bat' and 'BAT' { push(@found, $File::Find::name); } } }, $dir); print "$_\n" foreach (@found);
    Might need a bit of tweaking, but I think it's usually better to use modules than to call external programs.
Re: short dir listing
by blokhead (Monsignor) on Oct 23, 2002 at 17:54 UTC
    The backticks are interpolating your string a second time, see the example here:
    my $cmd = "echo \\t\\t"; print "$cmd\n"; ### prints: echo \t\t print `$cmd`; ### prints: tt
    So either double the number of backslashes, use quotemeta on the string before you send it to the backticks, or change the first line of my example to use single quotes.

    Update: On second thought, maybe that's not what's happening. On my system, the backslashes were being interpolated the second time by the shell, not the backticks.. At least I think so ;) You're using windows, so I'm not sure what is happening.

    blokhead

      $cmd = quotemeta($cmd); RESULT: cmd = dir\ \/b\ L\:\\Dir\\To\\Scan\\\*\.bat Parameter format not correct - "b\".

        Either use forward slashes in the dir name instead of backslashes or escape the backslashes in your dir name.

        $dir = 'L:/Dir/To/Scan'; # or $dir = "L:\\Dir\\To\\Scan";

        «Rich36»