sum#

Add up every value in the list and return the numerical total.

תקציר#

my $total = sum @values;
my $total = sum 1..10;           # 55

מה מוחזר#

A single number - an integer if every argument summed as an integer, a float otherwise. Integer arithmetic wraps on overflow rather than promoting, matching upstream. For an empty list, sum returns undef for backwards compatibility; if that is awkward use sum0 instead.

דוגמאות#

my $n = sum 3, 9, 12;            # 24
my $n = sum @bar, @baz;          # concatenated lists
my $n = sum();                   # undef
my $n = sum map { length } @s;   # total length of all strings

מקרי קצה#

  • Empty list returns undef. Use sum0 for a 0 default.

  • Mixing ints and floats promotes the running total to a float.

  • Non-numeric strings are coerced via the usual numification.

הבדלים מן ה-upstream#

Fully compatible with upstream.

ראו גם#

  • sum0 - same as sum, but returns 0 for an empty list.

  • product - multiplies rather than adds.

  • reduce - the generic reduction when sum is not specific enough.