[Solved] Populate an array by splitting a string


It looks like your code is essentially working. It’s just your checking logic that makes no sense. I’d do the following:

use strict;
use warnings;

if (@ARGV != 1) {
    print STDERR "Usage: $0 <consensus fasta file>\n";
    exit 1;
}

open my $fh, '<', $ARGV[0] or die "$0: cannot open $ARGV[0]: $!\n";

my @consensus;
while (my $line = readline $fh) {
    next if $line =~ /^>/;

    $line =~ s/\s+//g;
    push @consensus, split //, $line;
}

print "N = ", scalar @consensus, "\n";

Main things to note:

  • Error messages should go to STDERR, not STDOUT.
  • If an error occurs, the program should exit with an error code, not keep running.
  • Error messages should include the name of the program and the reason for the error.
  • chomp is redundant if you’re going to remove all whitespace anyway.
  • As you’re processing the input line by line, you can just keep pushing elements to the end of @consensus. At the end of the loop it’ll have accumulated all characters across all lines.
  • Examining @consensus within the loop makes little sense as it hasn’t finished building yet. Only after the loop do we have all characters we’re interested in.

1

solved Populate an array by splitting a string