in reply to intermix list of items
btw, the compare function is suppose to return -1, 0, +1, not just 0 and 1, so I expect your sort has some amount of randomness to it.
Maybe you want something like:
sub intermix { my $a_prime = join('.', reverse(split(/\./, $a))); my $b_prime = join('.', reverse(split(/\./, $b))); $a_prime cmp $b_prime } my @list = ('10.1.1.1', '10.1.1.2', '10.2.2.1', '10.2.2.2'); @list = sort intermix @list; use Data::Dumper; print Dumper(@list); __END__ output ====== $VAR1 = '10.1.1.1'; $VAR2 = '10.2.2.1'; $VAR3 = '10.1.1.2'; $VAR4 = '10.2.2.2';
Almost the same, but more efficient:
sub intermix { my $a_prime = reverse($a); my $b_prime = reverse($b); $a_prime cmp $b_prime } my @list = ('10.1.1.1', '10.1.1.2', '10.2.2.1', '10.2.2.2'); @list = sort intermix @list; use Data::Dumper; print Dumper(@list); __END__ output ====== $VAR1 = '10.1.1.1'; $VAR2 = '10.2.2.1'; $VAR3 = '10.1.1.2'; $VAR4 = '10.2.2.2';
This is the same thing as the last, but probably more efficient, especially for longer lists:
my @list = ('10.1.1.1', '10.1.1.2', '10.2.2.1', '10.2.2.2'); @list = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, ''.reverse($_) ] } @list; use Data::Dumper; print Dumper(@list); __END__ output ====== $VAR1 = '10.1.1.1'; $VAR2 = '10.2.2.1'; $VAR3 = '10.1.1.2'; $VAR4 = '10.2.2.2';
Note: Given addresses of the form 'a.b.c.d', the above snippets only work well if there is there is a common 'd' of for every 'a.b.c' in the list.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: intermix list of items
by ikegami (Patriarch) on Oct 10, 2004 at 18:42 UTC |
In Section
Seekers of Perl Wisdom