-
Notifications
You must be signed in to change notification settings - Fork 2
/
SAM_reader.pm
109 lines (78 loc) · 1.59 KB
/
SAM_reader.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package SAM_reader;
use strict;
use warnings;
use Carp;
use SAM_entry;
sub new {
my $packagename = shift;
my $filename = shift;
unless ($filename) {
confess "Error, need SAM filename as parameter";
}
my $self = { filename => $filename,
_next => undef,
_fh => undef,
};
bless ($self, $packagename);
$self->_init();
return($self);
}
####
sub _init {
my ($self) = @_;
if ($self->{filename} =~ /\.bam$/) {
open ($self->{_fh}, "samtools view $self->{filename} |") or confess "Error, cannot open file " . $self->{filename};
}
elsif ($self->{filename} =~ /\.gz$/) {
open ($self->{_fh}, "gunzip -c $self->{filename} | ") or confess "Error, cannot open file " . $self->{filename};
}
else {
open ($self->{_fh}, $self->{filename}) or confess "Error, cannot open file " . $self->{filename};
}
$self->_advance();
return;
}
####
sub _advance {
my ($self) = @_;
my $fh = $self->{_fh};
my $next_line = <$fh>;
while (defined ($next_line) && ($next_line =~ /^\@/ || $next_line !~ /\w/)) { ## skip over sam headers
$next_line = <$fh>;
}
if ($next_line) {
$self->{_next} = new SAM_entry($next_line);
}
else {
$self->{_next} = undef;
}
return;
}
####
sub has_next {
my $self = shift;
if (defined $self->{_next}) {
return(1);
}
else {
return(0);
}
}
####
sub get_next {
my $self = shift;
my $next_entry = $self->{_next};
$self->_advance();
if (defined $next_entry) {
return($next_entry);
}
else {
return(undef);
}
}
####
sub preview_next {
my $self = shift;
return($self->{_next});
}
1;