in reply to Multiplying together the numers in an array

use List::Util qw[ reduce ]; my @a = 2..6; print reduce{ $a*=$b } @a; 720

Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail

Replies are listed 'Best First'.
Re: Re: Multiplying together the numers in an array
by Anomynous Monk (Scribe) on Apr 09, 2004 at 01:26 UTC
    Is that *= intended as an optimization? I'd expect just *.

      It wasn't intended at all. I started out with the postfix for loop and then though, reduce would avoid the temp var and modified the line, leaving the *= behind.

      That said, it does appear to run approximately 20% quicker which might come in handy some day.


      Examine what is said, not who speaks.
      "Efficiency is intelligent laziness." -David Dunham
      "Think for yourself!" - Abigail

      To be completely honest, *= is just a short hand for

      $total = $total * $_;
      It is a holdover from C and is actually pretty useful as shorthand.

        Yes, I understand what *= does; the point is that reduce { $a *= $b } produces the same result as reduce { $a * $b } and the latter expresses the intention better (but the former is faster).