[英]How can I print to a variable instead of a file, in Perl?
如何使用Perl打印到變量?
我一直在研究一個程序,它以高度冗長的方式記錄它的迭代進度......
print $loghandle $some_message;
但是,我還想有選擇地將一些消息打印到不同的文件中。 當然,我可以將代碼撒上......
print $loghandle $some_message
print $otherloghandle $some_message
或者將整個業務重寫為一個功能。 等等。
我想要做的就是在打開$ loghandle時做一些魔術,這樣當我print
時,我實際上只是對一個變量做一個sprintf
ish操作(稱之為$current_iteration
),所以當我得到到決策點我可以做這樣的事......
print $real_log_file $current_iteration;
print $other_real_log_file $current_iteration if($condition);
我很確定我在某個地方見過這樣的東西,但我不知道它在哪里或在哪里看。
編輯:File :: Tee在某種程度上在* nix上解決了這個問題,但我在Windows上運行。
你的意思是IO :: Scalar嗎? 允許您使用文件句柄語義寫入變量。
如果要進行選擇性日志記錄,可以控制記錄哪些消息以及記錄哪些消息,請使用Log :: Log4perl 。 這將節省你一堆時間搞亂tie
和其他黑魔法。
您可以使用File :: Tee將文件句柄拆分為多個輸出流。
use File::Tee;
open my $fh, '>', 'logfile.txt' or die $!;
tee( $fh, '>', 'otherlogfile.txt' ) if $condition;
print $fh $current_iteration; # will also go to otherlogfile.txt
# if $condition was true
Perlfaq5推薦使用Tie :: FileHandle :: Multiplex打印到多個文件。
源代碼非常簡單,應該很容易使用每個句柄過濾器進行修改。
聲音就像你想要tie
檔文件一樣。
my $x;
# printing to $fh will update the variable $x
# when you close $fh, it will print $x to a filehandle depending
# on code in the function Print_to_variable::CLOSE
tie $fh, "Print_to_variable", \$x, $output_fh1, $output_fh2;
print $fh "stuff";
print $fh "more stuff";
close $fh;
sub Print_to_variable::TIEHANDLE {
my ($class, $ref, $fh1, $fh2) = @_;
my $self = {};
$self->{ref} = $ref;
$self->{output_fh1} = $fh1;
$self->{output_fh2} = $fh2;
bless $self, "Print_to_variable";
$self;
}
sub Print_to_variable::PRINT {
my ($self,@list);
${$self->{ref}} .= join "", @list;
}
sub Print_to_variable::CLOSE {
my $self = shift;
my $text = ${$self->{ref}};
if ( &myCondition1($text) ) { # ... how you decide where to print
print {$self->{output_fh1}} $text;
} else {
print {$self->{output_fh1}} $text;
}
}
這是一個巨大的黑客,我認為mobrule的解決方案或(特別是)Sinan的Log4Perl解決方案是我有時間的方式。
但是,這就是我正在使用的,作為完成的事情:
sub print_to_var($$) {
my($rx_var, $scalar) = @_;
$$rx_var .= $scalar;
}
print_to_var \$logvar, $message;
#...later on...
print $somefile $logvar;
編輯:
由於這是社區維基,因此Perl將函數的參數別名化是沒有價值的。 這意味着你可以寫下這個:
sub print_to_var($$) {
$_[0] .= $_[1];
}
然后說:
my $foo = "OH HAI. ";
print_to_var $foo, "I ARE HELO KITTIE.";
say $foo; # OH HAI. I ARE HELO KITTIE.
這不是一個特別大的黑客,雖然print_to_var
比打字更多.
是。
這是HELO KITTIE:
helo kittie http://blogs.philadelphiaweekly.com/style/files/2008/11/hello-kitty-color.gif
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.