Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Answer: How do I write my own sorting routine?

( #739227=categorized answer: print w/ replies, xml ) Need Help??

Q&A > sorting > How do I write my own sorting routine? 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), }, # ref => http://ckp.made-it.com/t1234.html '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' ];

Comment on Answer: How do I write my own sorting routine?
Download Code
Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (11)
As of 2015-07-28 16:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (258 votes), past polls