2

我有以下代码

#!/usr/bin/perl
use Tie::File;

tie my @last_id, 'Tie::File', 'last_id.txt' or die "Unable to open this file !$i";
print @last_id[0];

exit;

和一个以last_id.txt类似名称命名的文件

1
2
3
4
5
6

当我运行程序时,没有任何输出。我试过了$last_id[0],但还是一无所获。:/

我安装了最新的 ActivePerl。

编辑:

现在我收到Unable to open this file消息,但该文件与程序源文件存在于同一目录中。

4

2 回答 2

6

正如你所说,@last_id[0]是错误的,应该是$last_id[0]。但这不会导致您看到的问题。

请注意,程序不会last_id.txt在与 Perl 源文件相同的目录中查找,除非它也是当前工作目录。

您应该首先将tie行中使用的错误变量更改为$!这样

tie my @last_id, 'Tie::File', 'last_id.txt'
    or die "Unable to open this file: $!";

因为变量$i不包含任何有用的东西。这会告诉你失败的原因tie,这可能是没有这样的文件或目录以外的东西。

您还应该use strictuse warnings程序开始时,因为这将标记容易忽略的简单错误。

最后,尝试通过添加绝对路径来完全限定文件名。这将解决程序默认查找错误目录的问题。


更新

如果问题是您没有对该文件的写入权限,那么您可以通过以只读方式打开它来修复它。

您需要Fcntl模块来定义O_RDONLY常量,因此将其放在程序的顶部

use Fcntl 'O_RDONLY';

然后tie声明是这样的

tie my @last_id, 'Tie::File', 'last_id.txt', mode => O_RDONLY
    or die "Unable to open this file: $!";
于 2012-06-15T06:15:25.283 回答
1

如果您使用绝对路径,问题应该会消失

BEGIN {
    use File::Spec;
    use File::Basename qw' dirname ';
    use vars qw' $thisfile $thisdir ';
    $thisfile = File::Spec->rel2abs(__FILE__);
    $thisdir  = dirname($thisfile);
}
...
tie ... "$thisdir/last_id.txt"
于 2012-06-15T06:15:53.487 回答