【问题标题】:Capture Output to stream and store as a string variable捕获输出以流式传输并存储为字符串变量
【发布时间】:2014-08-29 03:04:43
【问题描述】:

虽然这个问题与“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 中的任何函数返回字符串的另一种方法

【问题讨论】:

    标签: string perl stream bioperl


    【解决方案1】:

    您可以将标准输出重定向到变量,

    my $captured;
    {
      local *STDOUT = do { open my $fh, ">", \$captured; $fh };
      $treeOut->write_tree($tree);
    }
    print $captured;
    

    【讨论】:

    • 那是獾。谢谢!
    【解决方案2】:

    通过设置 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);
    

    运行此脚本会将 newick 字符串打印到您的终端,正如您所期望的那样。如果你使用Bio::Phylo(我推荐),有一个to_string 方法(IIRC),所以你不必创建一个对象来打印你的树,你可以做say $tree->to_string

    【讨论】:

    • 啊,这更具体到手头的问题。感谢您提供有关 Bio::Phylo 的信息
    猜你喜欢
    • 2020-10-02
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    相关资源
    最近更新 更多