roibrodo has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

I have an array of hashes of arrays of arrays... I want to sort the arrays in the array of arrays in a specific hash according to the first element in each array.

This seems to work:

my @sorted = sort { $$a[0] <=> $$b[0] } @{$simulations[$simulation_in +dex]->{"SPECIAL"} }; $simulations[$simulation_index]->{"SPECIAL"} =\@sorted;

but the following, which for me seems the same (except without the temporary @sorted) - returns "Odd number of elements in anonymous hash at..."

$simulations[$simulation_index]->{"SPECIAL"} = \{sort {$$a[0] <=> $$b[ +0] } @{$simulations[$simulation_index]->"SPECIAL"} }};

Replies are listed 'Best First'.
Re: Odd number of elements in anon hash
by almut (Canon) on Jun 01, 2010 at 13:14 UTC

    For one, you're missing a curly before "SPECIAL".  But I think you rather want

    $simulations[$simulation_index]->{"SPECIAL"} = [ sort {$$a[0] <=> $$b[ +0] } @{$simulations[$simulation_index]->{"SPECIAL"} } ];

    i.e., the anonymous array [ ... ] would correspond to your original \@sorted.

    What you have is a reference to a hashref (\{ ... }), where the anonymous hash complains when initialized with an odd number of elements from the sort results.

      Thanks! I guess I'm not so familiar with the basics of "referencing" (I'm not even sure if that's the right name).

      so, when you use [ ... ] - does it return a reference to the enclosed an array? I think I was taught to use something like \@{...}. Does it mean the curly should be used only for hashes?

        [ ... ] returns a reference to an anonymous array.

        { ... } returns a reference to an anonymous hash.  In the appropriate syntactic context like assignment, that is.  Curlies are used for various things, for example a block, or to group/disambiguate when dereferencing, like @{ $obj->method_that_returns_an_arrayref() }.

Re: Odd number of elements in anon hash
by jethro (Monsignor) on Jun 01, 2010 at 13:11 UTC
    [$simulation_index]->"SPECIAL"} [$simulation_index]->{"SPECIAL"} ^