问题描述
我需要改变我的例行程序并将最终的输出文件进行 gzip 压缩.我试图找出对 perl 子例程中调用的已处理文件进行 gzip 压缩的最佳方法是什么.
I need to alter my routine and have the final outfile be gzipped. I'm trying to figure out what is the best way to gzip a processed file called within a perl subroutine.
例如,我有一个创建文件 (extract_data) 的子例程.这是主循环和子程序:
For example, I have a sub routine that creates the file (extract_data). Here's the main loop and sub routine:
foreach my $tblist (@tblist)
{
chomp $tblist;
extract_data($dbh, $tblist);
};
$dbh->disconnect;
sub extract_data
{
my($dbh, $tblist) = @_;
my $final_file = "/home/proc/$node-$tblist.dat";
open (my $out_fh, '>', $final_file) or die "cannot create $final_file: $!";
my $sth = $dbh->prepare("...");
$sth->execute();
while (my($uid, $hostnm,$col1,$col2,$col3,$upd,$col5) = $sth->fetchrow_array() ) {
print $out_fh "__my_key__^A$uid^Ehost^A$hostnm^Ecol1^A$col1^Ecol2^A$col2^Ecol3^A$col3^Ecol4^A$upd^Ecol5^A$col5^D";
}
$sth->finish;
close $out_fh or die "Failed to close file: $!";
};
我是在主文件中还是在子文件中执行 gzip?这样做的最佳方法是什么?那么我的新文件将是 $final_file =/home/proc/$node-$tblist.dat.gz
Do I do the gzip within the main or with the sub? What is the best way to do so?Then my new file would be $final_file =/home/proc/$node-$tblist.dat.gz
谢谢.
推荐答案
我知道有一些模块可以在不使用外部程序的情况下做到这一点,但是因为我比我更了解如何使用 gzip
了解如何使用这些模块,我只需打开一个流程到 gzip
并称它为一天.
I know there are modules to do this without using external programs, but since I understand how to use gzip
a lot better than I understand how to use those modules, I just open a process to gzip
and call it a day.
open (my $gzip_fh, "| /bin/gzip -c > $final_file.gz") or die "error starting gzip $!";
...
while (... = $sth->fetchrow_array()) {
print $gzip_fh "__my_key__^A$uid^Ehost^A$hostname..."; # uncompressed data
}
...
close $gzip_fh;
这篇关于perl - 创建 gzip 文件的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!