jeudi 11 février 2016

Perl: Reading file, grabbing specific lines and writing new files

I have a single input file that has the following format:

ATOM      1  CAY GLY X   1      -0.084   0.026  -0.058  1.00  2.67      PEP   
ATOM      2  HY1 GLY X   1      -0.448   1.075  -0.037  1.00  0.00      PEP 
.....
END
ATOM      1  CAY GLY X   1      -0.084   0.026  -0.058  1.00  2.67      PEP   
ATOM      2  HY1 GLY X   1      -0.448   1.075  -0.037  1.00  0.00      PEP
.....
END

This pattern repeats 1000 times. I'd like to read the input file and print all the lines between ATOM and END to an output file with a unique name (i.e. output001.pdb). This process needs to occur repeatedly until all the lines of the input file are read. A sample output file would look like this (output001.pdb):

ATOM      1  CAY GLY X   1      -0.084   0.026  -0.058  1.00  2.67      PEP   
ATOM      2  HY1 GLY X   1      -0.448   1.075  -0.037  1.00  0.00      PEP
.....
END

This is my code thus far:

#!/usr/bin/perl
use strict;
use warnings;

my $input = 'all.pdb';

open my $input_fh, '<', $input or die $!;

my @lines;
my @fh;
while ( <$input_fh> ) {
    chomp;
    if ($lines =~ m/ATOM/ .. m/END/ ) {
    for my $i (1 .. 1000) {
    open $fh[$i], '>', "file-$i" or die $!;
 }       
    print {$fh[$i]} $lines;
    }
 } 
 close ($fh[$i]);
 close ($input_fh);

I am not sure if my matching statement is correct given an array. Any suggestions on improvement are greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire