The foreach () loop I am trying to rewrite as a map {} is:
  foreach (sort { $a <=> $b } keys %hash) { push @c, \@{$hash{$_}}; }
My question is:  "Is this even possible, considering what is going on in the foreach () and what I am pushing (an array ref to a two dimensional array, see read more for the gory details)?"  My gut reation is the loop can be rewritten, but the solution escapes me.

Click on read more to see the full context.



The intent of this function is to merge two, two dimensional arrays and return the merged array.  The first and second elements (array indicies 0 and 1, respectivly) are left alone in the merge because the first is text and the second is what I key off of (munging my keys would generally be considered a Bad Thing and text does not play well with mathematical operators).
sub merge { my @a; my @b; { my $a_ref = shift; my $b_ref = shift; @a = @{$a_ref}; @b = @{$b_ref}; } my %hash; my @c; for(my $x = 0; $x <= $#b; $x++) { $hash{$b[$x][1]} = \@{$b[$x]};} for(my $x = 0; $x <= $#a; $x++) { if((exists $hash{$a[$x][1]}) && (defined $hash{$a[$x][1]})) { for(my $y = 2; $y <= $#{$hash{$a[$x][1]}}; $y++) { $hash{$a[$x][1]}[$y] = ($hash{$a[$x][1]}[$y] + $a[$x][$y]) / + 2; } } else { $hash{$a[$x][1]} = \@{$a[$x]}; } } foreach (sort { $a <=> $b } keys %hash) { push @c, \@{$hash{$_}}; } return @c; }
Update: Removed prototype.


In reply to How do I rewrite this foreach() loop as a map{} ? by northwind

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.