我是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";

09-12 15:50