Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: put every sequence of a file in a different output file

by kennethk (Abbot)
on Jun 13, 2013 at 15:09 UTC ( #1038770=note: print w/replies, xml ) Need Help??

in reply to put every sequence of a file in a different output file

How do you define a 'sequence'? How can you tell when you've moved from one to another? Are the sequences listed in series, or are they mixed together in some way? And while I'm at it, what have you tried and what didn't work? See How do I post a question effectively?.

In terms of transforming one file to a series of files, your code might look something like:

my $fh; my $i = 0; while (my $line = <$in>) { if (new_sequence_test($line)) { $i++; open $fh, '>', "seq_$i" or die "Open fail seq_$i: $!\n"; } print $fh $line; }

Update: Now that you've added input and code, I can say a little more. First, while not strictly necessary, strict will help you catch a lot of potential issues and will make variable scoping intent more obvious. See Use strict warnings and diagnostics or die.

When you say while($seq=<IN>), you read in one line of your file. Your split assumes you are slurping your whole file. And especially if file is 'huge', you probably don't want to store it all in memory. Assuming your sequences are split by empty lines, you could modify my already posted code to accomplish your task.

my $fh; my $i = 0; while (my $line = <$in>) { if (!$fh or $line !~ /\S/) { $i++; open $fh, '>', "seq_$i" or die "Open fail seq_$i: $!\n"; } print $fh $line; }

You could also do this very simply by modifying $/, but I suspect that solution would be unclear to you.

#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

Replies are listed 'Best First'.
Re^2: put every sequence of a file in a different output file
by bingalee (Acolyte) on Jun 13, 2013 at 16:10 UTC

    Thank you, Ill try your code. Mine didnt work, it put every line of the sequence into a new file, I guess i went wrong at the split.Can you tell me what should I have done instead-just so that I know what I did wrong

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1038770]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2018-06-21 18:43 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (118 votes). Check out past polls.