CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Sort, exclude with a pattern match?

 



mrhedin
Novice

Feb 11, 2015, 2:09 AM

Post #1 of 3 (2887 views)
Sort, exclude with a pattern match? Can't Post

Hello!

I've got a file with project numbers and street names that I read into an array:

A1---Dstreet
A2---Cstreet
A3---Bstreet
A4---Astreet

I'd like to sort these streetnames alphabetically.

The following:
my(@sorted_array) = sort { substr($a, 5) cmp substr($b, 5) } @array

does not work as the project number increases in lenghth. Is there a way to put a pattern matching into the substr to not include the project number and 3 dashes like: m/^A[0123456789]+---/


BillKSmith
Veteran

Feb 11, 2015, 5:06 AM

Post #2 of 3 (2882 views)
Re: [mrhedin] Sort, exclude with a pattern match? [In reply to] Can't Post

For small arrays you can use:

Code
use strict; 
use warnings;
my @array = ( qw( A1---Dstreet A2---Bstreet A3---Cstreet A4---Astreet ) );
my(@sorted_array) = sort { street($a) cmp street($b) } @array ;
$" ="\n";
print "@sorted_array\n";

sub street{
my $x = shift;
my ($st) = $x =~ m/^A\d+---(\w+)/;
return $st;
}


OUTPUT:

Code
A4---Astreet 
A2---Bstreet
A3---Cstreet
A1---Dstreet

Good Luck,
Bill


mrhedin
Novice

Feb 11, 2015, 7:44 AM

Post #3 of 3 (2875 views)
Re: [BillKSmith] Sort, exclude with a pattern match? [In reply to] Can't Post

Thanks, worked just fine that!

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives