是的,有多种方法可以做到这一点,但必须有一个规范的、最有效的、最简洁的方法。我会添加我所知道的答案,然后看看哪个能脱颖而出。
明确一下,问题是如何最好地将文件内容读入字符串中。 每个答案提供一种解决方案。
是的,有多种方法可以做到这一点,但必须有一个规范的、最有效的、最简洁的方法。我会添加我所知道的答案,然后看看哪个能脱颖而出。
明确一下,问题是如何最好地将文件内容读入字符串中。 每个答案提供一种解决方案。
对于一行命令,通常可以使用-0
开关(与-n
一起使用)使perl一次性读取整个文件(如果文件不包含任何空字节):
perl -n0e 'print "content is in $_\n"' filename
-0777
:perl -n0777e 'print length' filename
没有人提到过read或sysread,所以这里有一个简单快速的方法:
my $string;
{
open my $fh, '<', $file or die "Can't open $file: $!";
read $fh, $string, -s $file; # or sysread
close $fh;
}
调整特殊的记录分隔符变量$/
undef $/;
open FH, '<', $filename or die "$!\n";
my $contents = <FH>;
close FH;
这是最糟糕的做法之一!(请参见评论。)
open(F, $filename) or die "OPENING $filename: $!\n";
@lines = <F>;
close(F);
$string = join('', @lines);
cat $filename
"可用,这是完全合理的。虽然效率低下,但这并不一定是唯一需要考虑的因素。 - Mr.Reeopen(IN, "<$filename");
$contents = join('', <IN>);
close(IN);
细节:
<IN>
是一个文件描述符,如果赋值给一个列表变量/上下文,则返回一个行的列表(也称为数组)。
join
接受一个分隔符和一组行,并返回将所有行连接在一起的字符串。来源:https://perldoc.perl.org/functions/join)。
open
以"<"作为文件名前缀,以读取模式打开文件。
我经常使用 join 结构来处理一行代码,例如 perl -e '$_=join("",<>);s/multiline_regex/replacement_string/gms;print'
。m/s 选项支持多行正则表达式,请参阅 https://perldoc.perl.org/perlre。