Perl Open:没有这样的文件或目录。

时间:2022-05-01 00:31:46

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.

我尝试将目录中的每个文本文件读入一个变量,然后打印前100个字符,包括换行符。然而,Perl说文件并不存在,即使它们确实存在。

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?

它正在查找正确的文件,我确定文件存在。当我尝试使用这个方法来打开一个文件,而不是通过一个数组来获取每个文件时,它可以正常工作。这里有什么明显的东西我忽略了吗?

1 个解决方案

#1


4  

A better solution is to use readdir() instead (or File::Find if you ever want to do it recursively):

一个更好的解决方案是使用readdir()代替(或文件:如果您想要递归地执行它):

my $dir = "C:\\SomeFiles";

opendir(my $dh, $dir) || die "$!";

while (my $file = readdir($dh)) {
    if ($file =~ /\\.txt$/i) {
        print $file . "\n";
        my $txt = do {
            local $/ = undef;
            open(my $ff, "<", "$dir\\$file") || die "$!";
            <$ff>;
        };
        print substr($txt, 0, 100) . "\n";
    }
}

closedir($dh);

#1


4  

A better solution is to use readdir() instead (or File::Find if you ever want to do it recursively):

一个更好的解决方案是使用readdir()代替(或文件:如果您想要递归地执行它):

my $dir = "C:\\SomeFiles";

opendir(my $dh, $dir) || die "$!";

while (my $file = readdir($dh)) {
    if ($file =~ /\\.txt$/i) {
        print $file . "\n";
        my $txt = do {
            local $/ = undef;
            open(my $ff, "<", "$dir\\$file") || die "$!";
            <$ff>;
        };
        print substr($txt, 0, 100) . "\n";
    }
}

closedir($dh);