in reply to array sorting

Don't rely on that sort of thing (string interpolation, etc). Here's a good way:

print join(" ", sort @animals);

Or you could do this:

{ local $, = " "; print sort( @animals ); }

The latter method has the advantage of not creating a temporary second copy of the array in the form of a string as the result of join. This second method simply uses the list separator special variable $, to put a space between each list element as it is printed.


Dave

Replies are listed 'Best First'.
Re: array sorting
by Abigail-II (Bishop) on Jan 29, 2004 at 10:17 UTC
    Don't rely on that sort of thing (string interpolation, etc).
    Huh? Why is that? Does string interpolation only work half the time?

    I prefer "@array" over join " ", @array any day, and twice on Mondays. It's less messy:

    print "The first results are [@first]; the second are [@second]\n" +;
    vs.
    print "The first results are [", join (" ", @first), "; the second are [", join (" ", @second), "]\n";
    And pity you if you forget to leave off a set of parens.

    Abigail

      I understand what you're saying Abigail, and it makes absolute sense that if all you want is an array interpolated into a string with single spaces between elements, you'll use "@array". But he was trying to sort, and wanted the results to be output with single-spaces between each element. Fine, but he was going about it by inventing syntaxes that simply didn't do what he wanted. For one, putting "@array" in quotes as an argument to sort.

      And though interpolation has its place, you probably wouldn't recommend this (except for maybe in an obfu:

      print "@{[sort @array]}";

      Or maybe you would. There is always more than one way to do it. Though this method probably creates two copies of @array; one being an anonyomous array, and the second being the interpolated string.

      Anyway, thanks for pointing out the overstatement of my post. You are (as is often the case) correct.


      Dave