willk1980 has asked for the wisdom of the Perl Monks concerning the following question:
Hi,
I'm trying to write some simple code to sort some lines from a log file. Each line in the log file lists a message reference, and which part (out of a total count) that particular line is.
E.g.
Message reference 1, part 1 of 2
Message reference 1, part 2 of 2
I need to sort all the parts to a particular reference in ascending order and then return the log line number.
I've started work on trying to do this with perl hashes, but being a perl newbie, I'm struggling to get the return references. If anybody can help to point me in the right direction that would be much appreciated.
Using my sample code a data (below), I can currently print out
Ref: 1, parts: 1, 2, 3
Ref: 2, parts: 2, 3, 4
Ideally I want it to show
Ref 1, lines 5, 4, 6
Ref 2, lines 17, 18, 16
but I'm stuck trying to figure out how to pull out the key from %Data, given the part number associated with a reference.
Hopefully that makes some sort of sense.
#!/usr/bin/perl use strict; use warnings; my %Data = ( 04 => 'BQADAQMB (part 2 of 3 of message reference 1)', 05 => 'BQADAQMC (part 1 of 3 of message reference 1)', 06 => 'BQADAQMD (part 3 of 3 of message reference 1)', 16 => 'BggEAAIDAQ== (part 4 of 3 of message reference 2)', 17 => 'BggEAAIDAg== (part 2 of 3 of message reference 2)', 18 => 'BggEAAIDAw== (part 3 of 3 of message reference 2)', ); my %table; foreach my $key (sort keys %Data) { my $lValue = $Data{$key}; my @array = split ' ', $lValue; my $lPartStart = $array[2]; my $lPartEnd = $array[4]; my $lReference = $array[8]; chop($lReference); $table{$lReference} = [] unless exists $table{$lReference}; push @{$table{$lReference}}, $lPartStart; } foreach my $lReference (sort keys %table) { print "Ref: $lReference, parts: "; my @parts = @{$table{$lReference}}; print join ', ', sort @parts; print "\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Help needed sorting data with multiple associated hashes
by tangent (Parson) on Feb 26, 2013 at 01:47 UTC | |
by willk1980 (Novice) on Feb 27, 2013 at 17:15 UTC |