in reply to read files one by one in directory and redirct output to a file

You've commented out a bunch of code, why? It's unclear what problem you're having, and unclear how which code is relevant to the question. Please take the time to read and follow How do I post a question effectively? and SSCCE - if you follow that advice, we will be able to provide help much more efficiently.

Just a guess, but perhaps readdir is returning directories as well as just files? And as huck pointed out, the filenames returned by readdir don't include the directory name. Here, I'm using catfile from File::Spec to prefix the directory name to the filename, no_upwards from the same module to filter directory entries like . (curdir) and .. (parent dir), and -f to filter out only files. The sort is optional.

use File::Spec::Functions qw/no_upwards catfile/; opendir my $dh, $dirname or die "$dirname: $!"; my @files = grep {-f} map {catfile $dirname, $_} sort +no_upwards readdir $dh; closedir $dh;

Update: Fixed: "sort no_upwards" was not correct, but the -f test was hiding the issue.

Replies are listed 'Best First'.
Re^2: read files one by one in directory and redirct output to a file
by TonyNY (Beadle) on Jul 06, 2018 at 12:29 UTC

    Many apologies for the confusion. Basically what I am trying to do is read the content of all the files in a specific directory and redirect the output to one text file. e.g. 3 small log files.

      Basically what I am trying to do is read the content of all the files in a specific directory and redirect the output to one text file. e.g. 3 small log files.

      See my previous post(s). I see no need to "read the content" of the files because you are not doing any processing of the input. Treat them all as binary files and slam them together as a single output file using either "copy" on Windows or "cp" on Unix. If for some reason that doesn't meet your requirements, then give a short example with a couple of dummy files showing the problem. I don't see any "red flags" for performance issues here. But in general reading files line by line in text mode will be much slower than using an O/S command to append all of the files into a single file using a binary mode copy, even considering the overhead of launching the O/S command.