-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort_scaffolds_and_print_lengths.pl
89 lines (60 loc) · 1.73 KB
/
sort_scaffolds_and_print_lengths.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env perl
use strict;
use warnings;
##prints in the output file the lengths of contigs sorted from longest to shortest
#Usage:perl $0 input_assembly_fasta
my $out_all_lengths = "lengths_assembly.txt";
my $filename = shift @ARGV;
#Reads the fasta assembly in a hash (header -> sequence)
my %headers_scaffolds = &read_fasta_hash($filename);
#returns lenghts of scaffolds from longest to shortest
my @lengths =&get_lengths(values %headers_scaffolds);
open(my $fh_out, ">", $out_all_lengths) or die "Could not open file $out_all_lengths:$!\n";
foreach (@lengths){
print {$fh_out} "$_\n";
}
close $fh_out;
################################################################################################""
sub read_fasta_hash{
###Reads fasta into a hash
##It takes into account fasta files in interleaved format
open(my $fh, "<", $filename) or die "Could not open file $filename:$!\n";
my @lengths;
my $sequence = "";
my %hash_of_fasta;
my $header;
my $counter;
while (my $line = <$fh>){
chomp $line;
if ($line =~ m/>/){
++$counter;
if ($counter == 1){
$header = $line;
$hash_of_fasta{$line} = "";
}
else{
$hash_of_fasta{$header} = $sequence;
$sequence = "";
$header = $line;
}
}
else{
$sequence .= $line;
}
}
$hash_of_fasta{$header} = $sequence;
return %hash_of_fasta
}
########################################################################
sub get_lengths{
#Returns a list of lengths of scaffolds in reverse order (i.e., longest to shortest)
#Input: list of sequences (contigs)
my @contigs = @_;
my @list_lengths;
foreach (@contigs){
my $len = length($_);
push(@list_lengths, $len);
}
my @list_lengths_sorted = sort { $b <=> $a } @list_lengths;
return @list_lengths_sorted;
}