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

Greetings Monks,

Is there a way to do this:

for (0..9){ $t[0] += $data[$_][0]; $t[1] += $data[$_][1]; $t[2] += $data[$_][2]; $t[3] += $data[$_][3]; $t[4] += $data[$_][4]; }
without having to type essentially the same line five times?

I assume I would use an inner loop of some kind, but I don't know the perl haiku to reuse $_ since I've already used it in the (0..9) loop.

The context, if it makes a difference, is that @data is an AoA holding columnar data and @t is the row that totals each column.

Thanks in advance for any advice.

Replies are listed 'Best First'.
Re: scoping/localizing of $_
by GrandFather (Saint) on Jul 06, 2007 at 02:15 UTC
    for my $index (0..9){ $t[$_] += $data[$index][$_] for 0 .. 4; }

    Update: fixed sigil for t (was @)


    DWIM is Perl's answer to Gödel
      Beautiful, exactly what I was hoping for. Thank you!
Re: scoping/localizing of $_
by lestrrat (Deacon) on Jul 06, 2007 at 02:12 UTC
    for my $outer (0..9) { for my $inner (0..4) { $t[$inner] += $data[$outer][$inner]; } }