in reply to foreach loop

if ($line =~ /^\@/) { print $chro,"\n" if length $chro; $chro = $line; }

Replies are listed 'Best First'.
Re^2: foreach loop
by morio56 (Initiate) on May 04, 2011 at 17:17 UTC
    thanks for that. However, adding this line to my code only outputs:
    @chr1 @chr2 nnnnn... what I'd really like to have is: @chr1 nnnnnnnnn... @chr2 nnnnn....

      This uses ikegami's approach; this will print the previous $chro as soon as a new '@' is found. You seem to want to print $sequence at the same time. This moves the print statements inside the loop. Also, you need to reset sequence after the new @ is found. If you would give us something more detailed than 'nnnn' we could see where things should go. Try using __DATA__ next time to hold some sample data for everyone to see.

      use warnings; use strict; print "Using __DATA__ sample cns file:\n"; #chomp($t = <STDIN>); #open(THE, $t) or die "Can not open file: $!\n"; #@data = <THE>; my @data = <DATA>; #close THE; my $sequence=""; my $chro; foreach my $line (@data) { if ($line =~ /^\@/) { print $chro if length $chro; $chro = $line; print $sequence; $sequence = ""; } elsif ($line =~ /^[a-zA-Z]/) { $sequence .= $line; } else { print "no match: \$line=$line\n" } } #prints the last one, I'm sure theres a better way print $chro if length $chro; print $sequence,"\n"; __DATA__ @chr1 ACAAGATGCCATTGTCCCCCGGCCTCCTGCTGCTGCTGCTCTCCGGGGCCACGGCCACCGCTGCCCTGCC CCTGGAGGGTGGCCCCACCGGCCGAGACAGCGAGCATATGCAGGAAGCGGCAGGAATAAGGAAAAGCAGC @chr2 CTCCTGACTTTCCTCGCTTGGTGGTTTGAGTGGACCTCCCAGGCCAGTGCCGGGCCCCTCATAGGAGAGG AAGCTCGGGAGGTGGCCAGGCGGCAGGAAGGCGCACCCCCCCAGCAATCCGCGCGCCGGGACAGAATGCC @chr55 CTGCAGGAACTTCTTCTGGAAGACCTTCTCCTCCTGCAAATAAAACCTCACCCATGAATGCTCACGCAAG

      Update: would be better to replace the foreach with while (my $line=<DATA>) and get rid of @data. Especially since the files will probably be large.

        Thanks. This seem to work with the print. It appears to me though that the print is done after each iteration. Is there a way to retain the values of @chr and $sequence for each iteration so that they can be accessed outside the foreach loop? The data am dealing with is actually nnnnnnnnn i.e an fq sequence file and what am showing here is just part of it.
        _DATA_ @chr1 nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn @chr2 nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn @chr4 nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn @chr5 nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn