Perl:STDOUT/the shell 命令的输出直接到一个数组
Perl: STDOUT/the output of shell command to an array directly
我必须访问 shell 命令 - Perl 脚本中的配置单元,所以我使用 `...`。
假设 `hive ... ...` 的结果包含 100000000 行并且大小为 20GB。
我想要实现的是这样的:
@array = `hive ... ...`;
`` 是否自动知道使用“\n”作为分隔符将每行分成@array?
我能想到的两种方法是(但在这种情况下有问题):
$temp = `hive ... ...`;
@array = split ( "\n", $temp );
undef $temp;
这种方式的问题是,如果这种情况下hive的输出太大,$temp无法存储输出,导致segmentation fault core dump。
或
`hive ... ... 1>temp.txt`;
open ( FP, <, "temp.txt" );
while (<FP>)
{
chomp;
push @array, $_;
}
close FP;
`rm temp.txt`;
但是这种方式太慢了,因为它会先将结果写入硬盘。
有没有办法在不使用任何 'temporary container' 的情况下将 shell 命令的输出直接写入数组?
非常感谢您的帮助。
@array = `command`;
事实上,确实将 command
的每一行输出放入了 @array
的自己的元素中。无需将输出加载到标量中并 split
自己加载。
但是存储在数组中的 20GB 输出(由于 Perl 存储数据的方式,可能是该数量的 2-3 倍)仍然会给您的系统带来巨大的压力。
您问题的真正解决方案是通过 IO 句柄流式传输命令的输出,一次处理一行,而不必一次将所有输出加载到内存中。方法是使用 Perl 的 open
命令:
open my $fh, "-|", "command";
open my $fh, "command |";
-|
filemode 或附加到命令的 |
告诉 Perl 运行 一个外部命令,并使该命令的输出在文件句柄中可用 $fh
.
现在迭代文件句柄以一次接收一行输出。
while (<$fh>) {
# one line of output is now in $_
do_something($_);
}
close $fh;
我必须访问 shell 命令 - Perl 脚本中的配置单元,所以我使用 `...`。 假设 `hive ... ...` 的结果包含 100000000 行并且大小为 20GB。 我想要实现的是这样的:
@array = `hive ... ...`;
`` 是否自动知道使用“\n”作为分隔符将每行分成@array?
我能想到的两种方法是(但在这种情况下有问题):
$temp = `hive ... ...`;
@array = split ( "\n", $temp );
undef $temp;
这种方式的问题是,如果这种情况下hive的输出太大,$temp无法存储输出,导致segmentation fault core dump。
或
`hive ... ... 1>temp.txt`;
open ( FP, <, "temp.txt" );
while (<FP>)
{
chomp;
push @array, $_;
}
close FP;
`rm temp.txt`;
但是这种方式太慢了,因为它会先将结果写入硬盘。
有没有办法在不使用任何 'temporary container' 的情况下将 shell 命令的输出直接写入数组?
非常感谢您的帮助。
@array = `command`;
事实上,确实将 command
的每一行输出放入了 @array
的自己的元素中。无需将输出加载到标量中并 split
自己加载。
但是存储在数组中的 20GB 输出(由于 Perl 存储数据的方式,可能是该数量的 2-3 倍)仍然会给您的系统带来巨大的压力。
您问题的真正解决方案是通过 IO 句柄流式传输命令的输出,一次处理一行,而不必一次将所有输出加载到内存中。方法是使用 Perl 的 open
命令:
open my $fh, "-|", "command";
open my $fh, "command |";
-|
filemode 或附加到命令的 |
告诉 Perl 运行 一个外部命令,并使该命令的输出在文件句柄中可用 $fh
.
现在迭代文件句柄以一次接收一行输出。
while (<$fh>) {
# one line of output is now in $_
do_something($_);
}
close $fh;