All,
I remember reading that in relatively recent versions of Perl, a recursive function called by sort would result in a segfault. I don't know the particulars and may not even be remembering correctly. I decided to try my luck here and was happily suprised to find out that not only did it not segfault - it actually worked*.

I then decided to try and convert the code to use the goto &sub form to see if it made any difference in performance. See Pure Perl tail call optimization for more information.

#!/usr/bin/perl use strict; use warnings; my @data = map {chomp; [ split '/' ] } <DATA>; @data = map { join '/', @$_ } sort my_sort @data; print $_,$/ for @data; sub my_sort { my $i = $_[0] || 0; if ( defined $a->[$i] && defined $b->[$i] ) { if ( my $result = $a->[$i] <=> $b->[$i] ) { return $result; } ++$_[0]; goto &my_sort; } return defined $a->[$i] ? 1 : -1; } __DATA__ 0/1/2/3 0 0/4/5/6 0/4 0/1 0/1/2 0/4/5 0/10/111/145 0/10/111 0/10
This b0rk on my box (perl -V output available upon request). I confirmed that the function worked correctly when not called as a parameter to sort. After "playing" around, I discovered the following change made it start working again.
#@data = map { join '/', @$_ } sort my_sort @data; @data = map { join '/', @$_ } sort { my_sort() } @data;
Can anyone shed any light on what is going on here? This is purely for my own education and does not reflect what I would be doing in production code.

Cheers - L~R

* - It works when the data does not contain duplicates

Update: In a nutshell, autovivication of @_ with goto &sub is broke when using the sort SUBNAME LIST prototype but not the sort BLOCK LIST prototype. I still have no idea why though!


In reply to Sorting, recursion, and tail-call optimizations by Limbic~Region

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.