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

Having the following line I get just the filename. How can I modify it to get all path including the file name?
my $directory; @files = grep {-f "$directory/$_" && /\.dat$/i} readdir DIR;

I would like to get: c:\temp\file1.dat

Right now I just get: file1.dat

Replies are listed 'Best First'.
Re: Get fullpath of file using grep
by choroba (Cardinal) on Jan 28, 2015 at 14:15 UTC
    You can use map:
    my $directory = '...'; opendir my $DIR, $directory or die $!; my @files = grep /\.dat$/i && -f, map "$directory/$_", readdir $DIR;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Why chain grep() and map() if you can just use grep()?

      my $dir = "/tmp"; opendir my $dh, $dir or die "opendir: $!"; my @files = grep { $_ = "$dir/$_"; -f && m/\.dat$/ } readdir($dh);

      It works because grep() makes $_ an alias for a list element so it can be modified in-place. Some caution is advised however (see perlfunc entry for grep() for details).

      PS This code may also be a bit more efficient as it doesn't create a copy of an array returned by readdir() while doing map() but I'm not 100% sure.

        Why chain grep() and map() if you can just use grep()?
        Because I agree with Perl Best Practices on "Never modify $_ in a list function" (p 114).
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Works! Thanks
Re: Get fullpath of file using grep
by RichardK (Parson) on Jan 28, 2015 at 15:12 UTC

    or use glob.

    my @files = glob ("$dir/*.dat $dir/*.DAT");

    But watch out for directory names that contain spaces, you may need to use bsd_glob instead.