in reply to Perl List files in directory

I managed to get it working with open dir, i placed the files under a new directory.

the problem is that now I'm getting everything, even sub-directories and i only want the xml files

opendir(dir, new_dir) or die "Cannot open dir : $!"; @files = grep {"*.xml"} readdir DIR;

can someone tell me what i'm missing?

Replies are listed 'Best First'.
Re^2: Perl List files in directory
by Anonymous Monk on Apr 22, 2014 at 14:55 UTC

    I found the answer:

    @files = grep {-f "$dir/$_" && m/.xml/} readdir DIR;

    Thanks for the help people

      I'd suggest a small tweak to that:

      @files = grep {-f "$dir/$_" && /\.xml$/i} readdir DIR;

      Because otherwise the regular expression would have matched a file named "fooxml.bar" as well. Also, this now matches the extension case-insensitively, just in case.

        Hi,

        I have tried your tweak, but now i'm getting an error:

        Error = Illegal seak at ./script.pl line 28

        $directory = "/opt/tmp/"; opendir(DIR, $directory) or die "\nCannot open dir : $!\n"; @files = grep {-f "$directory/$_" && /\.xml$/i} readdir or die "Error += $!"; closedir(DIR);

        Can someone help me?