#!/usr/bin/perl -w
use strict;
my $bam = shift;
my $tmp = "/tmp/tmpNameList";
use List::Util qw(sum);
`samtools view $bam | cut -f1 > $tmp`;
`wc -l $tmp`;
open NAMES, $tmp;
my %hash;
while (<NAMES>) {
chomp;
my $id = $_;
$hash{$id} = 1;
}
my @values = values %hash;
my $readsNum = sum @values;
print "File: $bam\n";
print "Sum: $readsNum\n";
Maybe you could just use the hash of perl, If the sort | uniq command is source consuming. Treat the id as the key, sign its corresponding value as 1. Iteratively reading the id list, the same id still get the same value in light of multiple alignment would yield many same ids. After the hash construction, simply sum up all the value would give you how many reads actually in bam.
I think samtools -c command would yield the alignment number, which is often confused with reads number. Once you allow multiple alignment during your reads alignment, the number by samtools -c would be greatly larger than the real reads number in a bam file.
Even the pari-end alignement file could be counted with this easy perl script, as long as the id of each pair are same, just like the output of STAR. In other words, in the fastq, you would see abcdefg/1 for read1, abcdef/2 for read2 for example, in STAR the /1 and /2 are erased, leaving abcdefg for the read id.
in the output folder you should find the file align_summary.txt with this information