我是 Perl 脚本的新手。
我想对文件进行读写操作。我将以读写模式(+<)打开一个文件,并将写入一个文件。现在,我想读取我之前写入的文件。下面是我的代码:
#!/usr/bin/perl
`touch file.txt`; #Create a file as opening the file in +< mode
open (OUTFILE, "+<file.txt") or die "Can't open file : $!";
print OUTFILE "Hello, welcome to File handling operations in perl\n"; #write into the file
$line = <OUTFILE>; #read from the file
print "$line\n"; #display the read contents.
当我显示读取的内容时,它显示一个空行。但文件“file.txt”有数据
Hello, welcome to File handling operations in perl
为什么我无法阅读内容。我的代码是否错误或者我遗漏了什么。
最佳答案
问题是您的文件句柄位置位于您所写入的行之后。使用seek
函数将“光标”移回顶部,然后再次阅读。
一个示例,带有一些额外的注释:
#!/usr/bin/env perl
# use some recommended safeguards
use strict;
use warnings;
my $filename = 'file.txt';
`touch $filename`;
# use indirect filehandle, and 3 argument form of open
open (my $handle, "+<", $filename) or die "Can't open file $filename : $!";
# btw good job on checking open sucess!
print $handle "Hello, welcome to File handling operations in perl\n";
# seek back to the top of the file
seek $handle, 0, 0;
my $line = <$handle>;
print "$line\n";
如果您要进行大量阅读和写作,您可能想尝试(并非每个人都建议这样做)使用 Tie::File
它可以让你像数组一样对待文件;按行号访问行(自动写入换行符)。
#!/usr/bin/env perl
# use some recommended safeguards
use strict;
use warnings;
use Tie::File;
my $filename = 'file.txt';
tie my @file, 'Tie::File', $filename
or die "Can't open/tie file $filename : $!";
# note file not emptied if it already exists
push @file, "Hello, welcome to File handling operations in perl";
push @file, "Some more stuff";
print "$file[0]\n";
关于linux - perl 脚本中的读写操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10902648/