brunoV (owner)

Revisions

gist: 113594 Download_button fork
public
Public Clone URL: git://gist.github.com/113594.git
Embed All Files: show embed
dirwatch-translate.pl #
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
#!/usr/bin/perl
use Modern::Perl;
use POE qw(Component::DirWatch::Object::NewFile);
use Bio::SeqIO;
use Bio::Seq;
use File::Temp;
use File::Copy qw(move);
use Gtk2::Notify -init, "Translator";
 
my $watcher = POE::Component::DirWatch::Object::NewFile->new(
    directory => '/home/brunov/translate',
    filter => sub { $_[0] =~ /\.fasta/ && -f $_[1] }, # Only fasta
    callback => sub {
        eval { translate(@_) };
    },
    interval => 1, # Watch interval
);
 
# Different ways of passing a message to the user.
my %notify_with = (
    gtk2 => sub { Gtk2::Notify->new( 'Attention', shift )->show },
    stdout => sub { say shift },
    stderr => sub { warn shift, "\n" },
    nothing => sub { return },
);
 
sub translate {
 
    # Translate the input file from dna to protein, replacing the
    # original file. Sequences that are already protein remain
    # untouched.
 
    my ( $filename, $fullpath ) = @_;
 
    # Input sequence stream.
    my $seqI = Bio::SeqIO->new( -file => $fullpath );
 
    # Output sequence stream.
    my $tempfile = File::Temp->new( SUFFIX => '.fasta' )->filename;
    my $seqO = Bio::SeqIO->new( -file => ">$tempfile", format => 'fasta' );
 
    # Translate dna sequences and write to temp file.
    my $outcome = 0;
    while ( my $seq = $seqI->next_seq ) {
        if ( $seq->alphabet eq 'dna' ) {
            $seq = $seq->translate;
            $outcome = 1;
        }
        $seqO->write_seq($seq);
    }
 
    $_->close for ( $seqI, $seqO );
 
    # Replace the original file with the temporary one with the
    # translated sequences.
    # $outcome will be true only if seq is dna and move succeded.
    $outcome *= move( $tempfile, $fullpath );
 
    notify( $outcome, $filename, qw(gtk2 stderr) );
}
 
sub notify {
    my ( $success, $file, @mediums ) = @_;
 
    if ($success) {
        $notify_with{$_}->("Translated $file") for @mediums;
    } else {
        $notify_with{$_}->("$file not translated") for @mediums;
    }
 
    return 1;
}
 
$poe_kernel->run();