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



mrhedin
Novice

Feb 11, 2015, 2:09 AM


Views: 3513
Sort, exclude with a pattern match?

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


Views: 3508
Re: [mrhedin] Sort, exclude with a pattern match?

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


Views: 3501
Re: [BillKSmith] Sort, exclude with a pattern match?

Thanks, worked just fine that!