无法在 Perl 中关闭文件句柄

Unable to close file handle in Perl

我是 Perl 的新手,因为我试图在名为 test 的目录中的名为 data 的子目录中创建一个文本文件,我尝试编写以下代码,代码如下: -

#!/usr/bin/perl
use strict;
use warnings;
use Cwd qw(abs_path);
use File::Path qw(make_path remove_tree);
my $path = abs_path();
my @file = open(my $fh, '>>', '$path/test/data') or die "unable to create text file $!";
print $fh;
close $fh or die "unable to close file $fh $!\n";

它给了我以下错误:-

unable to close file GLOB(0x1d5ea68) Bad file descriptor

如果您能解释这里发生的事情,那将非常有帮助和感激?如何解决? 提前致谢。

该错误的意思是 $fh 不是打开的文件句柄。错误消息的 GLOB... 部分是文件句柄的字符串化。很可能 $path/test/ 不存在,所以 $fh 永远不会打开。 Open 不会创建目录组件,只会创建文件。首先使用 -e 检查它,并在必要时使用 mkdirmake_path 创建它。

您的 open or die 子句不起作用,因为您正在将 open 输出捕获到数组中,而这正是 or.

评估的内容

我赞扬你学习 Perl 来完成你的任务。以下是您应该阅读的内容,以解决这些问题并继续您的道路。

https://perldoc.pl/perl https://perldoc.pl/functions/open https://perldoc.pl/functions

HTH

open 失败,因此 $fh 不包含有效的文件句柄,这导致 close 失败。


open 正在返回一个错误,但您没有收到有关该错误的通知,因为您的检查不正确。因为 open 总是 returns 一个值,所以列表赋值总是 returns 1,所以 die 永远无法计算。 (如果需要更多详细信息,请参阅 。)

替换

my @file = open(...)
    or die "unable to create text file $!";

open(...)
    or die "unable to create text file $!";

至于为什么open失败,原因肯定是路径$path/test/data不存在。您实际上是在寻找名为 $path 的目录,因为单引号字符串文字不会插入。

替换

'$path/test/data'

"$path/test/data"

或者干脆

'test/data'

因为 $path 只包含当前目录。

不是您问题的真正答案,但我喜欢对文件 I/O 使用 Path::Tiny 模块。它比原始公开调用更容易使用,而且您不必为大多数任务寻找单独的模块。

#!/usr/bin/perl
use strict;
use warnings;
use Path::Tiny qw(path cwd);    # methods mkpath and remove_tree are available

my $file = cwd->child('test', 'data');
my $fh = $file->opena;  # dies on failure
print $fh;
close $fh or die "unable to close file $fh $!\n";

# But even easier to not bother with open/close and just do something like:
$file->append('...');