From dc97b2596fd2429ae31c4c4987127ff48d350a1e Mon Sep 17 00:00:00 2001 From: Mischa POSLAWSKY Date: Sat, 10 Dec 2022 01:12:57 +0100 Subject: [PATCH] sum calculation on demand and cached Automatic handling of any (re)use in calc(). --- barcat | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/barcat b/barcat index cb3282e..1fd0dd3 100755 --- a/barcat +++ b/barcat @@ -400,11 +400,9 @@ sub show_stat { $vars{partsum} = sum(0, grep {length} @values[$linemin .. $linemax]) if $linemin <= $linemax and ($opt{hidemin} or $opt{hidemax}); %vars = (%vars, - sum => sum(@order), min => $order[-1], max => $order[0], ); - $vars{avg} = $vars{sum} / @order; } say varfmt($opt{report}, \%vars); return 1; @@ -413,10 +411,16 @@ sub show_stat { sub calc { my ($func) = @_; if ($func eq 'avg') { - return sum(@order) / @order; + return calc('sum') / @order; } elsif ($func eq 'sum') { - return sum(@order); + state $cache; # avoid recount + state $cachednr = 0; # if unchanged + unless (@order == $cachednr) { + $cache = sum(@order); + $cachednr = @order; + } + return $cache; } elsif ($func =~ /\A([0-9.]+)v\z/) { $1 <= 100 or die( -- 2.30.0