【问题标题】:Convert string into array perl将字符串转换为数组 perl
【发布时间】:2021-05-01 13:27:05
【问题描述】:

我有一个脚本,它获取一个多 fasta 文件的标题并将它们推送到一个数组中。然后我想遍历这个数组来找到一个特定的模式并执行一些命令。

open(FH, '<', $ref_seq) or die $!;
while(<FH>){

    $line = $_;
    chomp $line;
    if(m/^>([^\s]+)/){
        $ref_header = $1;
        print "$ref_header\n";
        chomp $header;
        if($1 eq $header){
            $ref_header = $header;
            #print "header is $ref_header\n";
        } 
    } 
}

此代码打印标题如

chr1
chr2
chr3

如何将这些标头推送到数组中?

我尝试了以下代码,但它拆分了单个字母,而不是 $header_array[0]chr1

@header_array = split(/\n*/, $ref_header);
            print ("Here's the first element $header_array[0]");

任何帮助将不胜感激。

【问题讨论】:

    标签: arrays perl bioinformatics fasta


    【解决方案1】:

    如下所示缩短代码,去掉一些多余的语句,使用push。您可以结合push 和模式匹配:

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    use Carp;
    
    my $in_file = shift;
    my @headers;
    
    open my $in_fh, '<', $in_file or croak "cannot open $in_file: $!";
    while ( <$in_fh> ) {
        push @headers, />(\S+)/;
    }
    close $in_fh or croak "cannot close $in_file: $!";
    
    print "@headers";
    
    # Now, loop through headers and select the ones you need, for example:
    
    for my $header ( @headers ) {
        if ( $header =~ /foo/ ) {
            # do something
        }
    }
    

    以下是修复原始代码的一些建议:

    # Always use strict and use warnings.
    
    # Remove extra parens and make the error message more informative:
    open(FH, '<', $ref_seq) or die $!;
    while(<FH>){
    
        $line = $_;
        chomp $line;
        # [^\s] is simply \S:
        if(m/^>([^\s]+)/){
            $ref_header = $1;
            print "$ref_header\n";
            # where is $header coming from?
            chomp $header;
            # if the condition is satisfied, this assignment does not make sense:
            # $ref_header is already the same as $header:
            if($1 eq $header){
                $ref_header = $header;
                #print "header is $ref_header\n";
            } 
        } 
    }
    

    【讨论】:

      【解决方案2】:

      你可以使用push:

      push @header_array, $ref_header;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-07
        • 1970-01-01
        • 1970-01-01
        • 2017-11-27
        • 2015-07-10
        • 1970-01-01
        • 2011-06-18
        相关资源
        最近更新 更多