From 1d65d4be6b169a7b05e05a4961e0e0a059cbc1bf Mon Sep 17 00:00:00 2001 From: doug Date: Wed, 8 Oct 2014 21:07:26 -0400 Subject: [PATCH] Allow --count to accept expressions, just like --grep and --map - One of the reasons this is useful is you can fetch arbitratily nested items from the data section - Thanks to Avianna for the suggestion --- bin/log-defer-viz | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/bin/log-defer-viz b/bin/log-defer-viz index 4a7e411..a074811 100755 --- a/bin/log-defer-viz +++ b/bin/log-defer-viz @@ -125,12 +125,6 @@ if ($opt->{'data-only'}) { } -my $count = {}; - -foreach my $key (@{ $opt->{count} }) { - $count->{$key} = {}; -} - my $columns = $opt->{'timer-columns'}; @@ -138,7 +132,8 @@ my ($term_cols, $term_rows) = Term::Size::chars(*STDOUT{IO}); $columns = $term_cols if $term_cols; -## The _ sub is a shortcut for use in --grep and --map expressions, ie --grep "_->{data}" + +## The _ sub is a shortcut for use in --grep, --map, and --count expressions, ie --grep "_->{data}" sub _ () { $_ } if ($opt->{grep}) { @@ -152,6 +147,24 @@ if ($opt->{map}) { } +my $count = {}; +my $count_subs = {}; + +foreach my $key (@{ $opt->{count} }) { + if ($key =~ /^\w+$/) { + ## The original format for count arguments were keys to the data hash + $count_subs->{$key} = sub { $_[0]->{data}->{$key} }; + } else { + ## But the more general way is with an accessor + $count_subs->{$key} = eval('sub { local $_ = $_[0]; ' . $key . '}'); + die "Error compiling --count expression '$key' ($@)" if $@; + } + + $count->{$key} = {}; +} + + + unshift(@ARGV, '-') unless @ARGV; if (@ARGV > 1 && $opt->{follow}) { die "You've specified --follow but have also provided multiple files, which doesn't make sense. Did you mean to do this?"; @@ -266,8 +279,10 @@ sub handle_entry { if (@{ $opt->{count} }) { foreach my $key (@{ $opt->{count} }) { - if (exists $entry->{data}->{$key}) { - $count->{$key}->{$entry->{data}->{$key}} += 1; + my $val = $count_subs->{$key}->($entry); + + if (defined $val) { + $count->{$key}->{$val} += 1; } }