I'm trying to read every text file in a directory into a variable then print the first 100 characters, including line breaks. However, Perl says that the files don't exist even though they really do exist.
use strict; use warnings; my $dir = "C:\\SomeFiles"; my @flist; open(my $fh, "dir /a:-d /b $dir |") || die "$!"; while (<$fh>) { if ($_ =~ /.*(.txt)$/i) { push(@flist, $_); } } foreach my $f (@flist) { print "$dir\\$f"; my $txt = do { local $/ = undef; open(my $ff, "<", "$dir\\$f") || die "$!"; <$ff>; }; print substr($txt, 0, 100); } When I run the script, the following is written to the console:
C:\SomeFiles\file1.txt No such file or directory at script.pl line 19, <$fh> chunk 10. It's looking at the right file and I'm certain that the file exists. When I try using this method to open a single file rather than getting each file via an array with foreach, it works just fine. Is there something obvious that I've overlooked here?
chompread?chomp. You're not stripping the trailing end-of-line characters from your file names before you try to open them.C:\SomeFiles\C:\SomeFiles\file1.txt.