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

sub addup { my $total = 0; $total += $_ foreach @_; return $total; }
How can I replace this function with a built in?

Replies are listed 'Best First'.
(Ovid) Re: addup function?
by Ovid (Cardinal) on Jul 19, 2001 at 00:38 UTC
Re: addup function? => use Inline!
by grinder (Bishop) on Jul 19, 2001 at 02:12 UTC

    If you really, really want a built in method, then you could always write a C function and call that...

    #! /usr/bin/perl -w use strict; use Inline C => <<'ADDUP_END'; double addup( SV* stub, ... ) { double total = 0; int i; Inline_Stack_Vars; for( i = 0; i < Inline_Stack_Items; ++i ) { total += SvNV(Inline_Stack_Item(i)); } return total; } ADDUP_END my @a = (0..100); print addup(@a), "\n";

    But is it worth the effort?

    --
    g r i n d e r
Re: addup function?
by archon (Monk) on Jul 19, 2001 at 00:38 UTC
    well you could use
    map {$total += $_} @_;
    or
    $total += eval (join "+", @_)

    or any other number of abominations... but what's wrong with the way you're doing it now?

      eval (join "+", @_) is pretty good.

      I'm looking for a way to say it without using the middle-man $total variable.

      Is there a way to say it without resorting to an eval?

      Ideally I want a builtin that takes a list and an operator and does an eval (join "operator", @list) to produce a scalar.

      It's looking like there isn't one.

        the eval answer was a joke. it is far from pretty good and could get you in trouble with evil data.

        there is no builtin that does exactly what you want to do.

        Even though it's not a builtin function, List::Util's reduce function will do most of what you ask:
        my @list = (1, 2, 3, 4); my $sum = reduce { $a + $b } @list; # 10 my $mul = reduce { $a * $b } @list; # 24 my $min = reduce { $a - $b } @list; # -8 my $mod = reduce { $a % $b } @list; # 1 # etc
        ar0n ]