0

这对我来说很新,但是,我正在慢慢地接受它。

我需要打开一个文件,将第一行返回给 var 做一些事情,然后在事情成功后从文件中删除第一行。

在 mt 脚本中,除了第一行之外的所有内容都打印到屏幕上。

$file = 'test.txt';

system "tail -n+2 /home/username/public_html/adir/$file";

现在我在这里做了一些探索,发现:

system "sed -i '1d' home/username/public_html/adir/$file";

这应该删除文件内联的第一行。(我没试过)

如果我也可以将第一行返回到 $variable 来做一些事情,那将是完美的。

如果事情失败了,我可以将该行添加回文件中。

我知道我可以用一堆带有数组的 FILE < 和 > 来做到这一点,但似乎有点多。

文件很小,不到 100 行,每行 6 个字符。

我对为此追求 sed 或 tail 一无所知吗?

如何使用这些系统调用将删除的行作为 $line 返回?

感谢学习经验。

4

2 回答 2

3

我不喜欢将这个想法用于出色system()的任务。perl

怎么样?

use warnings;
use strict;

open my $fh, q[<], $ARGV[0] or die $!; 

## Read from the filehandle in scalar context, so it will read only
## first line.
my $first_line = <$fh>;

# do stuff with first line...

## And if stuff was successful, read left lines (all but the first one) and
## print them elsewhere. 
while ( <$fh> ) { 
    print;
}
于 2012-05-09T13:15:37.167 回答
1

听起来像是Tie::File非常适合的那种东西。

#!/usr/bin/perl

use strict;
use warnings;
use Tie::File;

my $file = 'test.txt';

tie my @array, 'Tie::File', $file or die "Count not tie file: $file: $!";

my $line = $array[0];

if (do_something_successfully()) {
  shift @array;
}
于 2012-05-09T13:37:19.580 回答