我怎么能得到存储在变量中的文件的最后几行?在linux上我会使用tail命令,如果它在文件中.
1) How can I do this in perl if the data is in a file?
2) How can I do this if the content of the file is in a variable?
Run Code Online (Sandbox Code Playgroud)
读取文件seek的末尾,靠近文件的末尾并开始阅读.例如,
open my $fh, '<', $file;
seek $fh, -1000, 2;
my @lines = <$fh>;
close $fh;
print "Last 5 lines of $file are: ", @lines[-5 .. -1];
Run Code Online (Sandbox Code Playgroud)
根据文件中的内容或想要查看的行数,您可能需要使用与-1000上面不同的幻数.
你也可以用变量做类似的事情
open my $fh, '<', \$the_variable;
seek $fh, -1000, 2;
Run Code Online (Sandbox Code Playgroud)
要不就
open my $fh, '<', \substr($the_variable, -1000);
Run Code Online (Sandbox Code Playgroud)
将为您提供一个产生最后1000个字符的I/O句柄$the_variable.
| 归档时间: |
|
| 查看次数: |
5487 次 |
| 最近记录: |