sort issue

B

Bogdan

Hi there,
I need to sort elements of of list/array by character. For instance I
got "hdisk1 hdisk10 hdisk11 hdisk2 hdisk3 ... " and need to have
"hdisk1 hdisk2 hdisk3 ... hdisk10 hdisk11 ..."
I can do that using external programs like
$ cat file_with_hdisks | sort -n -k1.6

but I'd like to do it in perl. Does anyone have any piece of code or
at least idea how to achieve that in as easy way as passible?

Thanks,
Bogdan
 
M

Matija Papec

X-Ftn-To: Bogdan

Hi there,
I need to sort elements of of list/array by character. For instance I
got "hdisk1 hdisk10 hdisk11 hdisk2 hdisk3 ... " and need to have
"hdisk1 hdisk2 hdisk3 ... hdisk10 hdisk11 ..."
I can do that using external programs like
$ cat file_with_hdisks | sort -n -k1.6

but I'd like to do it in perl. Does anyone have any piece of code or
at least idea how to achieve that in as easy way as passible?

http://www.google.com/search?q=schwartzian

#untested
my @arr = qw/hdisk1 hdisk10 hdisk11 hdisk2 hdisk3/;
@arr =
map $_->[0],
sort {
$a->[1] cmp $b->[1] ||
$a->[2] <=> $b->[2]
}
map [ $_, /(\w+)(\d+)/ ], @arr;
 
T

Tad McClellan

Bogdan said:
I need to sort elements of of list/array by character. For instance I ^^^^^^^^^^
got "hdisk1 hdisk10 hdisk11 hdisk2 hdisk3 ... "


That is not a "list/array", that is a string.

and need to have
"hdisk1 hdisk2 hdisk3 ... hdisk10 hdisk11 ..."


There are several Frequently Asked Questions about sorting,
have you already seen their answers?

I can do that using external programs like
$ cat file_with_hdisks | sort -n -k1.6


Why are you stopping at the 6th character when some of your pieces
have 7 characters? (eg. hdisk10).

You have a Useless Use Of Cat as well:

sort -n -k1.6 file_with_hdisks

but I'd like to do it in perl. Does anyone have any piece of code or
at least idea how to achieve that in as easy way as passible?


---------------------------
#!/usr/bin/perl
use strict;
use warnings;

my @parts = split /\s+/, 'hdisk1 hdisk10 hdisk11 hdisk2 hdisk3';
print "$_\n" for @parts; # before
print "----\n";

@parts = sort { substr($a, 5) <=> substr($b, 5) } @parts;
print "$_\n" for @parts; # after
 
M

Matija Papec

X-Ftn-To: John W. Krahn

John W. Krahn said:
$a->[1] cmp $b->[1] ||
$a->[2] <=> $b->[2]
}
map [ $_, /(\w+)(\d+)/ ], @arr;

Because \w includes \d and + is greedy, the third element will always be
one character. In other words, /(\w+)(\d+)/ is the same as
/(\w+)(\d)/. You probably want /(\w+?)(\d+)/ or /(\w*\D)(\d+)/ or
something else instead.

Yes, didn't look for greediness; tnx.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top