SaltedPork SaltedPork - 15 days ago 6
Perl Question

How do I store culmultive length of strings into an array with Perl

I have a file which has a series of lines that are made up of A's, C's, G's and T's. I want to find the length of those lines, make a list of the culmultive lengths (adding the lengths together sequentially), and putting that into an array. So far I have:

#! /usr/bin/perl -w
use strict;

my $input = $ARGV[0];
my %idSeq;
my (@ID, @Seq);

open (my $INPUT, "<$input") or die "unable to open $input";

while (<$INPUT>) {
if (my $culm_length = /^([AGCT]\w+)\n$/) {
length($culm_length) = $_;
push (@Seq, $1);

}
}
bla bla bla....


So far I think what I have written gives me an array of the length of individual lines. I want the culmultive lengths, any ideas?

Answer

With reference to your previous question How do I read strings into a hash in Perl which was put on hold, I think perhaps you want a running total of the lengths of the lines

I would write it this way. It keeps the running total in $total and pushes its value onto the @lengths array every time it changes

use strict;
use warnings 'all';

my ( $input ) = @ARGV;

open my $fh, '<', $input or die qq{unable to open "$input" for input: $!};

my @lengths;
my $total = 0;

while ( <$fh> ) {
    push @lengths, $total += length $1 if /^([ACGT]+)/;
}