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.


In reply to Re: intermix list of items by ikegami
in thread intermix list of items by tstock

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.