M
Michael Slass
I have a hash where the keys are strings and the values are integers.
I wanted to produce a report of the name/value pairs, sorted by the
integers in descending order.
I came up with this:
,----
| #!/usr/bin/perl -w
| use strict;
|
| my %hack_count;
| my @report;
|
| # read in ssh attempts from /var/log/messages*
| while (<>)
| {
| if (/sshd.+rhost=(\S+)/)
| {
| ++$hack_count{$1};
| }
| }
|
| # create a list of (count, ip) cells, sorted by count
| my ($ip, $count);
| while (($ip, $count) = each %hack_count)
| {
| push @report, [$count, $ip];
| }
|
| foreach (sort { $b->[0] <=> $a->[0]; } @report) {
| printf("%-50s\t%4d\n", $_->[1], $_->[0]);
| }
`----
Is there a way to combine the "each" and "push" statements so I don't
need the intermediate variables $ip and $count? The order of the
variables in the anonymous lists is not important; I just put the
numerical value first since I figured I'd remember to sort on the
first element of the anonymous lists.
Thanks.
I wanted to produce a report of the name/value pairs, sorted by the
integers in descending order.
I came up with this:
,----
| #!/usr/bin/perl -w
| use strict;
|
| my %hack_count;
| my @report;
|
| # read in ssh attempts from /var/log/messages*
| while (<>)
| {
| if (/sshd.+rhost=(\S+)/)
| {
| ++$hack_count{$1};
| }
| }
|
| # create a list of (count, ip) cells, sorted by count
| my ($ip, $count);
| while (($ip, $count) = each %hack_count)
| {
| push @report, [$count, $ip];
| }
|
| foreach (sort { $b->[0] <=> $a->[0]; } @report) {
| printf("%-50s\t%4d\n", $_->[1], $_->[0]);
| }
`----
Is there a way to combine the "each" and "push" statements so I don't
need the intermediate variables $ip and $count? The order of the
variables in the anonymous lists is not important; I just put the
numerical value first since I figured I'd remember to sort on the
first element of the anonymous lists.
Thanks.