我有以下代码
#!/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;
Run Code Online (Sandbox Code Playgroud)
和一个以last_id.txt这样的名字命名的文件
1
2
3
4
5
6
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,没有任何输出.我试过$last_id[0]但仍然没有.:/
我安装了最新的ActivePerl.
编辑:
现在我收到Unable to open this file消息,但该文件与程序源文件存在于同一目录中.
如你所说,@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: $!";
Run Code Online (Sandbox Code Playgroud)
因为变量$i没有任何用处.这将告诉你失败的原因tie,这可能不是这样的文件或目录.
你也应该use strict和use warnings你的程序的开始,因为这将标志简单的错误,很容易被忽视.
最后,尝试通过添加绝对路径来完全限定文件名.这将解决程序在默认情况下查找错误目录的问题.
更新
如果问题是您没有对该文件的写入权限,那么您可以通过以只读方式打开它来修复它.
您需要Fcntl模块来定义O_RDONLY常量,因此将它放在程序的顶部
use Fcntl 'O_RDONLY';
Run Code Online (Sandbox Code Playgroud)
然后tie声明是这样的
tie my @last_id, 'Tie::File', 'last_id.txt', mode => O_RDONLY
or die "Unable to open this file: $!";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
895 次 |
| 最近记录: |