Skip to content

Instantly share code, notes, and snippets.

@nylander
Created May 21, 2021 09:51
Show Gist options
  • Save nylander/6744f58f9ae0117d3abdb102138e4301 to your computer and use it in GitHub Desktop.
Save nylander/6744f58f9ae0117d3abdb102138e4301 to your computer and use it in GitHub Desktop.
Fasta to Nexus converter using BioPerl
#! /usr/bin/env perl
#
# Short description for fasta2nexus.pl
#
# Author nylander <johan.nylander@nrm.se>
# Version 0.1
# Copyright (C) 2021 nylander <johan.nylander@nrm.se>
# Modified On 2021-05-21 10:54
# Created 2021-05-21 10:54
#
use strict;
use warnings;
use Bio::AlignIO;
use Getopt::Long;
my $help = 0;
my $version = "1.0";
my $VERBOSE = 1;
GetOptions(
'V|version' => sub {print "$0 v$version\n"; exit;},
'help' => sub {print "Usage: $0 [--help] [--version] fastafile(s)\n"; exit;},
'verbose!' => \$VERBOSE,
);
if (! @ARGV) {
print STDERR "Usage: $0 [--help][--version][--noverbose] fastafile(s)\n";
exit;
}
while ( my $infile = shift(@ARGV) ) {
my $outfile = $infile . ".nexus";
my $in = Bio::AlignIO->new(
-format => 'fasta',
-file => $infile);
print STDERR "Found $infile..." if ($VERBOSE);
my $out = Bio::AlignIO->new(
-format => 'nexus',
-show_endblock => 0,
-show_symbols => 0,
-file => ">$outfile");
while ( my $aln = $in->next_aln ) {
$out->write_aln($aln);
}
if ( -e $outfile ) {
rename($outfile, $outfile . '.TmpnexusfilE');
open(my $IN, '<' . $outfile . '.TmpnexusfilE') or die $!;
open( my $OUT, '>' . $outfile) or die $!;
while (<$IN>) {
$_ =~ s/gap=-/gap=- missing=?/;
print $OUT $_;
}
close($IN);
close($OUT);
unlink $outfile . '.TmpnexusfilE';
print STDERR " wrote $outfile\n" if ($VERBOSE);
}
}
print STDERR "\nNOTE: make sure to manually check and adjust DATATYPE if having mixed data\n" if ($VERBOSE);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment