sort array on specific value in each element

Ken Elliott's picture

They have: 358 posts

Joined: Jun 1999

Hello,
Here is something I found which is exactly what I am looking for.

http://forums.devshed.com/archive/t-10863

I've tested it all kinds of ways and I can't get it to work. Here is my test version code:

#!/usr/bin/perl

@aa = ("1|a","3|c","5|e","2|b","7|i","4|d","6|h");



sub bName {
(split(/$sep/, lc($a)))[$field] cmp (split(/$sep/, lc($b)))[$field];
#cmp for comparing words
#dictionary order, ignoring case (w/o lc(), get ASCII order)
}

sub byNum {
(split(/$sep/, $a))[$field] <=> (split(/$sep/, $b))[$field];
#<=> for comparing numbers as values, notwords
}

print "Content-type:text/html\n\n";

$field = 1;
$sep = "|";
@bb = sort bName @aa;

foreach $a(@aa) {
print "$a<br>";
}
print "<p>Bz<br>";

foreach $b(@bb) {
print "$b<br>";
}
'

I can't get it to work and I can't think of another way to do it. Can someone shed some light on me =)

Thanks!
Ken

Pimpin like a pimp with an electrofied pimpin machine!

Ken Elliott's picture

They have: 358 posts

Joined: Jun 1999

where o where have all the brains gone!

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

Change:

$sep = "|";
'
to
$sep = "\\|";
'

Smiling

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

Btw, here's another way of doing it, based on another script:

#!/usr/bin/perl

@lines = ("3|c","1|a","5|e","2|b","7|i","4|d","6|h");

$sep   = "\\|";
$field = 1;

foreach (@lines) {
    push(@names, (split(/$sep/))[$field]);
}


sub by_name
{
    lc($names[$a]) cmp lc($names[$b]);
}


@sortedlines = @lines[sort (by_name (0..$#lines))];

foreach $line (@sortedlines) {
    print("$line\n");
}
'

They have: 1 posts

Joined: Jan 2005

Use Sort::Fields from cpan.org

Example (to sort from a comma-delimited array)

@carersorted = fieldsort '\|', [$sort_method], @carerdb;

Works like a dream. Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.