#!/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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment