【问题标题】:Print a variable which is inside two loops打印两个循环内的变量
【发布时间】:2016-12-13 12:35:15
【问题描述】:

我不知道如何逃脱。

我想打印两个循环内的变量$rfam_column。但是我不能只在$rfam_column 出现的地方之后写print 命令,因为我想打印其他将在循环之外的东西并将它们组合到打印的内容中。

如果我在这里做错了什么,我将不胜感激。

use warnings;
use strict;

my $in;
GetOptions('input' => \$in) or die;

if ( $in ) {

    my $input = $ARGV[0] or die;

    open (my $fh, '<', $input) or die "Can't open $input $!\n";
    chomp (my @db_file = <$fh>);
    close $fh;

    my @list = grep /RNA/, @db_file;

    my $column;
    my @column = ();

    foreach  $column ( @list ) {

        my @all_columns = split (/\t/, $column);
        my $rfam_column = $all_columns[0];

        # insert "|" between RFs

        foreach $_ ( $rfam_column ) {
            s/^/|/;
        }
    }
}

print "$rfam_column";
Global symbol "$rfam_column" requires explicit package name at script_vbeta.pl line 90.
Execution of script_vbeta.pl aborted due to compilation errors.

已编辑以包括输入的所有代码和信息-建议的输出:

输入文件是一个有n行vs n列的表格(我提取了几列,否则在一行中表示会很长):

RF00001 1302    5S ribosomal RNA
RF00006 1307    Vault RNA
RF00007 1308    U12 minor spliceosomal RNA
RF00008 1309    Hammerhead ribozyme (type III) 

输出应该是这样的:

|RF00001|RF00006|RF00007 

以及代码(用法:script.pl -i input_file):

use warnings;
use strict;
use Getopt::Long;
Getopt::Long::Configure("pass_through");


my $in;
GetOptions('input' => \$in) or die;

if ( $in ) {

    my $input = $ARGV[0] or die;

    open (my $fh, '<', $input) or die "Can't open $input $!\n";
    chomp (my @db_file = <$fh>);
    close $fh;

    my @list = grep /RNA/, @db_file;

    my $column;
    my @column = ();

    foreach  $column ( @list ) {

        my @all_columns = split (/\t/, $column);
        my $rfam_column = $all_columns[0];
        # insert "|" between RFs
        foreach $_ ( $rfam_column ) {
            s/^/|/;
        }
    }
}
print "$rfam_column";

【问题讨论】:

  • 显示样本输入文件(带有多个 RNA 行)以及您想要的输出
  • 请展示你的真实程序。您所显示的内容与 Undefined subroutine &amp;main::GetOptions 一起消失
  • 如果您将程序设计得更具可读性,这将对您有很大帮助。是的,我已经在这里为您完成了,以便我们自己阅读
  • 您错误地命名了$column 变量,该变量依次设置为输入文件中的每个@all_columns 包含该行中拆分为列的数据,$all_columns[0] 是当前行的第一列。对于外部for 循环的每次迭代,两者都会发生变化。我不知道这是否对应于对 Perl 的误解。
  • 谢谢你们。我是 Perl 和编程新手...我编辑了帖子,所以现在所有代码都可用了。

标签: perl


【解决方案1】:

我想打印循环之外的其他内容并将它们组合到 $rfam_column 内容中

您可以在print 中包含外部范围中的任何内容。您可以将 print 语句放在内部循环中

顺便说一句,我不知道你的意思

# insert "|" between RFs

foreach $_ ($rfam_column) {
    s/^/|/;
}

就是这样

$rfam_column =~ s/^/|/;

它只是在字符串的开头添加一个管道| 字符

什么是射频?

【讨论】:

  • 嗨 Borodin,例如,RF 是 RF0001 的缩写。我更改了替换函数的 foreach 循环。谢谢
【解决方案2】:

我想你想要

if ($in) {
    ...

    my @rfams;
    for my $row (@list) {
        my @fields = split(/\t/, $row);
        my $rfam = $fields[0];
        push @rfams, $rfam;
    }

    my $rfams = join('|', @rfams);
    print("$rfams\n");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-14
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多