in reply to split snafus

I'd use a regex to pull out the fields you are interested in then use split to chop em up. With a little cunning you can leverage map and a for (as a statement modifier) to get everything done in a fairly compact, but lucid way. Consider:

use warnings; use strict; my $data = <<'DATA'; Summary 51.58.214.48/dw109998bsw45 -> (1*Cisco_Power_Supply) (1*Cisco_ +CPU_Unit) (7*IETF_IF) (1*Cisco_Fan_Unit) (1*1213_Device) (2*Cisco_Mem +ory_Pool) Summary 51.58.220.21/dw108432bsw25 -> (6*Cisco_Power_Supply +) (1*Cisco_CPU_Unit) (333*IETF_IF) (6*Cisco_Fan_Unit) (1*1213_Device) + (2*Cisco_Memory_Pool)DATA DATA my %totals; $totals{$_->[1]} += $_->[0] for map {[split '\*']} $data =~ /\(([^)]*) +\)/g; print "$_: $totals{$_}\n" for sort keys %totals;

Prints:

1213_Device: 2 Cisco_CPU_Unit: 2 Cisco_Fan_Unit: 7 Cisco_Memory_Pool: 4 Cisco_Power_Supply: 7 IETF_IF: 340

Note the trick of putting the split inside a [] pair to create a two element array for each item the regex generates. The chunk to the left of the for builds a hash of totals keyed by item type.


Perl is environmentally friendly - it saves trees

Replies are listed 'Best First'.
Re^2: split snafus
by manav_gupta (Acolyte) on Jun 17, 2008 at 12:17 UTC
    geez. That'd take me a long time to get my head around it... Thanks! There's enough there for me to explore and learn :-)

      It should be more readable to do it like this:

      my %hFields; while ( $line =~ / \( (\d+) \* ([^)]+) \) /gx ) { $hFields{ $2 } += $1; }
        d'oh! Yeah, it all makes sense now ...
        Excellent references - just the stuff I was looking for. Thank you!