虽然这个问题与'BioPerl'有关,但我认为,这个问题可能比这更普遍。
基本上我已经产生了一个Bio::Tree::TreeI对象,我正试图将其转换为字符串变量。
我能接近将它转换为字符串变量的唯一方法是使用
将该树写入流:# a $tree = Bio::Tree::TreeI->new() (which I know is an actual tree as it prints to the terminal console)
my $treeOut = Bio::TreeIO->new(-format => 'newick')
$treeOut->write_tree($tree)
->write_tree的输出是"将树写入流",但我如何在字符串变量中捕获它,因为我找不到从Bio::TreeIO
您可以将标准输出重定向到变量
my $captured;
{
local *STDOUT = do { open my $fh, ">", $captured; $fh };
$treeOut->write_tree($tree);
}
print $captured;
通过为BioPerl对象设置文件句柄,有一种更简单的方法来实现相同的目标,我认为这不是一个hack。下面是一个例子:
#!/usr/bin/env perl
use strict;
use warnings;
use Bio::TreeIO;
my $treeio = Bio::TreeIO->new(-format => 'newick', -fh => *DATA);
my $treeout = Bio::TreeIO->new(-format => 'newick', -fh => *STDOUT);
while (my $tree = $treeio->next_tree) {
$treeout->write_tree($tree);
}
__DATA__
(A:9.70,(B:8.234,(C:7.932,(D:6.321,((E:2.342,F:2.321):4.231,((((G:4.561,H:3.721):3.9623,
I:3.645):2.341,J:4.893):4.671)):0.234):0.567):0.673):0.456);
运行此脚本将新提示字符串打印到终端,正如您所期望的那样。如果你使用Bio::Phylo(我推荐),有一个to_string
方法(IIRC),所以你不必创建一个对象来打印你的树,你可以只做say $tree->to_string
。