in reply to Sorting question...
I will also assume that all of the "keys" and "values" are delimited by a colon, and that colon cannot appear as a key nor a value. These are a lot of assumptions, but you didn't really define such things in your question.
my @records; { local $/ = "\n\n"; open IN, "<file.dat" or die "Cannot open data file.\n$!"; while ( my $record = <IN> ) { my @kv_pairs = split /\n/, $record; push @records, [@kv_pairs]; } close IN; } my @sorted_recs = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, (split /:\s*/, $_->[3])[1] ] } @records;
Ok, here's the walk-through...
First, set the input record separator to "\n\n" so that you read in entire blank-line-delimited records together. split the key/value pairs on "newline" characters, and push them into an array of arrayrefs (a list of lists, see perllol).
Next, perform a Schwartzian Transform. Use the 4th element of each anonymous arrayref held in @records. The forth element ([3]) contains "The global clock skew:...". Split that element on ":", and use the second half (the value) as what gets put into the ST container for comparison purposes within the sort.
Finally, the ST returns your original datastructure in sorted order.
If you wish to sort on multiple criteria, your ST will have to be just a little more complicated, and then your sort routine will have to have some "or" logical short-circuits to fall through to the next level if higher levels evaluate to equality during the sort.
I hope this helps. Kinda confusing, I know. But if you can define the spec a little better I might be able to help with a more robust (and probably slightly less complex) solution.
Note, the reason I used an array of arrays, instead of an array of hashes to store your datastructure, was because I assumed that you wanted to keep each record's lines in their original order. Since normal hashes don't have any concept of order, dumping your K/V pairs into a hash would have lost their original order within each record. If order is unimportant, an array of hashes could serve to reduce the complexity of the transform.
I also used the <=> comparison operator instead of cmp, because it looked to me like you're trying to sort on a numeric value.
Update: Fixed extraneous } character at the end of the code snippet. Sorry about that, hope this gets you going in the right direction.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Sorting question...
by Anonymous Monk on Jan 16, 2004 at 19:43 UTC | |
by davido (Cardinal) on Jan 17, 2004 at 05:08 UTC | |
by Anonymous Monk on Jan 17, 2004 at 20:34 UTC | |
by Roy Johnson (Monsignor) on Jan 16, 2004 at 20:02 UTC | |
by davido (Cardinal) on Jan 17, 2004 at 04:44 UTC |