in reply to Re^2: Print Max Hash
in thread Print Max Hash

I'm trying to only print the occurrence once

Not sure what you are trying to do. If you want to stop multiple records then just use a %seen{key} hash e.g.

#!perl use strict; my %seen = (); while ( my $line = <DATA> ) { next if $line =~ /Insufficent|CLEARED/; if ( $line =~ /SNMP/ ) { my @f = split /\|/, $line; my $node_ip = $f[4] || 'N/A'; my $message = $f[13]; my (undef,$ne) = split /[ &]+/,$f[15]; unless ( $seen{$ne}++ ){ printf "%-15s | %9s | %s \n", $node_ip, $ne, $message; } } } __DATA__ 143599203|No|NACK|ENA||Major|20180129054027||ARM|NSA|PRM|0|DCN|Insuffi +cient SNMP security settings|HN408-CP-1E-I|3176 && 1234|||||||No|| 143599356|No|NACK|ENA|192.168.0.1|Major|20180129054037||CLR|NSA|PRM|0| +DCN|CLEARED: Network element does not respond to SNMP requests|HN4000 +e|3176 && 12345|||||||No|| 143599357|No|NACK|ENA|192.168.0.2|Major|20180129054039||CLR|NSA|PRM|0| +DCN|CLEARED: Insufficient SNMP security settings|HN4000e|3176 && 1234 +56|||||||No|| 143599999|No|NACK|ENA|192.168.0.3|Major|20180129054529||ARM|NSA|PRM|0| +DCN|Network element does not respond to SNMP requests|HN4000e|3176 && + 7890|||||||No|| 143599999|No|NACK|ENA|192.168.0.3|Major|20180129054529||ARM|NSA|PRM|0| +DCN|Network element does not respond to SNMP requests|HN4000e|3176 && + 7890|||||||No|| 143599999|No|NACK|ENA|192.168.0.3|Major|20180129054529||ARM|NSA|PRM|0| +DCN|Network element does not respond to SNMP requests|HN4000e|3176 && + 7890|||||||No||
poj

Replies are listed 'Best First'.
Re^4: Print Max Hash
by bartrad (Beadle) on Jan 30, 2018 at 14:35 UTC

    Hi Poj, that worked a treat thank you.

    Suppose in my printf I wanted to show the count of how many times said $ne has occurred against the single entry for that $ne, how would I do that? Thanks again!

      Store the lines in a hash of arrays (HoA) (see perldsc) and print them after all the lines have been scanned/counted

      while ( my $line = <DATA> ) { next if $line =~ /Insufficent|CLEARED/; if ( $line =~ /SNMP/ ) { my @f = split /\|/, $line; my $node_ip = $f[4] || 'N/A'; my $message = $f[13]; my (undef,$ne) = split /[ &]+/,$f[15]; if ( $seen{$ne} ){ ++$seen{$ne}[0]; } else { $seen{$ne} = [ 1, $node_ip, $ne, $message ]; } } } for my $ne ( sort keys %seen ){ printf "%d | %-15s | %9s | %s \n", @{$seen{$ne}}; }
      poj

      You can't print the total number of occurrences alongside the individual items because you don't know that at the time you print, which is when you see the first of them. However, you could print totals as a summary after you have processed all the records because the %seen hash keeps count for you. Alternatively, defer printing until all records have been read, storing what you want to print as you go in an array (or hash if order is unimportant) that you can tack totals onto at the end of processing.

      Cheers,

      JohnGG