The stupid question is the question not asked PerlMonks

### Answer: How do I write my own sorting routine?

by poolpi (Hermit)
 on Jan 27, 2009 at 15:35 UTC Need Help??

Q&A > sorting > How do I write my own sorting routine? - Answer contributed by poolpi

```#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use Math::BigInt lib => 'GMP';

my @speeds =
( '10Mbps', '115kbps', 'Flash', '2Mbps', 'T1 LINE', 'Shocker' );

my ( @clean_speeds, @sorted_speeds );

my \$speed_re = {
'BPS' => qr/(\d+)\s*([KMGT])BPS/,    # 10MBPS
'T'   => qr/T(\d)\s*\w*/,            # T1 LINE
};

my \$bps  = Math::BigInt->new('2')->bpow(10);

my \$unit = {
'BPS' => {
K => \$bps->copy->bpow(0),
M => \$bps->copy->bpow(1),
G => \$bps->copy->bpow(2),
T => \$bps->copy->bpow(3),
},
'T' => {
1 => Math::BigInt->new('1544'),      # T1 = 1544   kbps
2 => Math::BigInt->new('6312'),      # T2 = 6312   kbps
3 => Math::BigInt->new('44736'),     # T3 = 44736  kbps
4 => Math::BigInt->new('274760'),    # T4 = 274760 kbps
},
};

for (@speeds) {
my \$speed = uc \$_;
\$speed =~ /(?:\$speed_re->{'BPS'}|\$speed_re->{'T'})/
? push @clean_speeds, \$speed
: warn "Unmatched speed: \$speed\n";
}

@sorted_speeds =
sort { net_speed(\$a) <=> net_speed(\$b) } @clean_speeds;

print Dumper \@sorted_speeds;

sub net_speed {
my \$speed = shift;
if ( \$speed =~ /\$speed_re->{'BPS'}/ ) {
Math::BigInt->new( \$unit->{'BPS'}->{\$2} )->bmul(\$1);
}
elsif ( \$speed =~ /\$speed_re->{'T'}/ ) {
Math::BigInt->new( \$unit->{'T'}->{\$1} );
}
}
__END__
Output:
------
Unmatched speed: FLASH
Unmatched speed: SHOCKER
\$VAR1 = [
'115KBPS',
'T1 LINE',
'2MBPS',
'10MBPS'
];

Create A New User
Chatterbox?
 [Dumu]: ambrus: it's about testing a file for being multiple possible file formats [ambrus]: In particular, you might want to detect the encoding of a HTML file from between utf-16 versus ascii-based and encoding given in a META tag. [ambrus]: Dumu: it should probably be safe to change the encoding if you rewind first with seek \$file, 0, 0 first [Dumu]: ambrus: good guess. I'm trying to contribute to a CPAN module, and the existing tests assume they're looking at text files [Dumu]: ambrus: thank you. I was seeking afterwards. I'll seek first. [jedikaiti]: Hello, Dumu! [Dumu]: hello again jedikaiti! thanks everyone today for being in the monastery!

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (8)
As of 2017-11-20 17:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
In order to be able to say "I know Perl", you must have:

Results (291 votes). Check out past polls.

Notices?