这对我来说很新,但我正在慢慢接受它。
我需要打开一个文件,将第一行返回到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";
应该删除内联文件的第一行。 (我没试过)
如果我还可以将第一行返回到$变量来执行操作,那将是完美的。
如果填充失败,我可以将该行添加回文件中。
我知道我可以用一堆FILE<和>但是,看起来有点多了。
文件很小,少于100行,每行6个字符。
我是否完全无法为此寻求sed或尾巴?
如何使用这些系统调用将删除的行作为$ line返回?
感谢您的学习经历。
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}