Tables like this:
<p>
Porpertity History
<p>
class Rate data
<p>
A1 5% 10
<p>
B1 3.5% 8
How to parse them into a hash or array?
开发者_StackOverflow社区Thanks a lot.
There are three ways we could parse this table. First, we need to open it and get to the data. I'm assuming that if the second column ends in a %
, it's a valid column:
#! /usr/bin/env perl
use strict;
use warnings;
open (MY_FILE, "data.txt")
or die qq(Can't open "data.txt" for reading\n);
my %myHash;
my %dataHash;
my %rateHash;
while (my $line = <MY_FILE>) {
my ($class, $rate, $data) = split (/\s+/, $line);
next (unless $rate =~ /%$/);
That part of the code will split the three items, and then the question is how to structure the hash. We could create two hashes (one for rate and one for data, and use the same key:
$rateHash{$class} = $rate;
$dataHash{$data} = $data;
Or, we could have our hash as a hash of hashes, and put both pieces in the same hash:
$myHash{$class}->{RATE} = $rate;
$myHash{$class}->{DATA} = $data;
You can now pull up either the rate or data in the same hash. You can also do it in one go:
%{$myHash{$class}} = ("RATE" => $rate, "DATA" => "$data");
I personally prefer the first one.
Another possibility is to combine the two into a single scalar:
$myHash{$class} = "$rate:$data"; #Assuming ":" doesn't appear in either.
My preference is to make it a hash of hashes (like in the second example). Then, create a class to handle the dirty work (Simple to do using Moose).
However, depending upon your programming skill, you might feel more comfortable with the double hash idea, or with combining the two values into a single hash.
精彩评论