我正在Perl中编写一个脚本,它从文件中读取并打印内容。 它正在读取文件而没有错误,但它不打印内容。
#!/usr/bin/perl
use warnings;
use strict;
use autodie;
my $dir = "/home/user/.fluxbox/.notify/notify";
if ( -e "$dir")
{
open(NOTE, "+>>", $dir) or die( "Error opening file! $!");
chomp(my @note = <NOTE>);
print "File Contents:\n";
print "@note\n";
close(NOTE) or die "Can't close $dir: $!";
}
输出:
Name "main::NOTE" used only once: possible typo at /path/to/script.pl line 13.
File Contents:
答案 0 :(得分:4)
当您打开附加文件时,文件末尾会留下文件偏移量,因此阅读将立即为您提供帮助。你需要seek
向后(可能你想要文件的开头),然后阅读会得到任何东西。由于你根本就没有写作,你应该只打开文件进行阅读(正如其他人所说的那样)
答案 1 :(得分:3)
http://www.perlfect.com/articles/perlfile.shtml
mode operand create truncate
read <
write > ✓ ✓
append >> ✓
Each of the above modes can also be prefixed with the + character
to allow for simultaneous reading and writing.
mode operand create truncate
read/write +<
read/write +> ✓ ✓
read/append +>> ✓
你正在使用read / append,所以它会读到EOF并从那里开始。您需要使用<
从文件的开头开始。
答案 2 :(得分:2)
该文件被截断,因为您正在为写入(和读取)打开它,如在C(和其他一些语言?)中那意味着如果文件已经存在则会截断该文件。如果您确实想要在文件中添加文本,则需要为追加(和阅读)打开它,在Perl中使用'+>>'
代替'+>'
。但是,您的脚本不会向该文件写入任何内容,并且您的描述表明您只想从中读取,而不是写入它,因此在这种情况下,您应该只打开它以便仅使用'<'
进行读取
此外,你永远不应该使用open
的双参数形式;总是使用三参数形式(在这种情况下,open(NOTE, '+>>', $dir)
)。
[seek][1]
来将位置设置为文件的开头,然后读取文件将为您提供其内容。
答案 3 :(得分:1)
你不知道它是否会收到错误,因为你从未检查过它们。添加
use autodie;
或正确检查您的退货值。 知道 readline
或print
成功的唯一方法是检查close
。
close(NOTE) || die "can't close $dir: $!";
您无法测试print
或readline
的值。你必须检查`close。
还有其他问题,但这是一个良好的开端。
现在验证文件中是否包含要读取的内容。统计它并确保你读了那么多字节。你怎么知道有什么东西要读?您的统计数据仅用于测试是否存在。它不测试大小,权限,甚至文件类型。
答案 4 :(得分:0)
open(NOTE, "+>>", $dir) or die( "Error opening file! $!");
您的问题是第二个参数,'+&gt;&gt;'。当您将其切换为<
时,它可以正常工作。我相信+>>
表示“写+追加”,而<
表示“读取”。
答案 5 :(得分:0)
我正在Perl中编写一个脚本,它从文件中读取并打印出来 内容。
您需要的是:
不是将整个文件读入内存,而是最好使用while
的逐行模式。使用chomp
将删除换行符,并显着减少输出,因此除非您需要,否则不要使用它。
您无需检查文件是否存在,因为open
和autodie
会为您处理此问题。此脚本也可以与命令行参数一起使用,例如script.pl filename.txt
。如果不是这样,请删除shift ||
。
<强>代码:强>
use strict;
use warnings;
use autodie;
my $file = shift || "/home/user/.fluxbox/.notify/notify";
open my $fh, '<', $file;
print "File contents:\n--------------\n";
print while (<$fh>);