linux - perl 脚本中的读写操作

标签 linux perl

我是 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/

相关文章:

将组条目写入/etc/group 的 Linux 函数

java - 关于JAVA和Linux的一些基本概念 : PATH variable in LINUX and class location by JVM

perl:我可以等 15 分钟,然后如果没有按下某个键,做点什么吗?

perl - 将 Moose 与 Test::Class 一起使用 - 构造函数问题

perl HTTP::GHTTP 设置传出 ip

mysql - Perl 从 xls 读取插入到 mysql

python - 如果另一个实例已经在运行,如何杀死 python 脚本及其子脚本

c - shell get segmentation fault 实现历史

linux - 用于嵌入式 Linux 的 LVDS 屏幕

perl - 循环遍历 perl 数组