|
Let's suppose you've got to read in a data file like this:
Date |Description | Income|Expenditure
01/24/2001 Ahmed's Camel Emporium 1147.99
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 235.00
|
|
How do we do it? You might think first to use split; however, since split
collapses blank fields, you'll never know whether a record was income or expenditure. Oops.
Well, you could always use substr:
while (<>) {
my $date = substr($_, 0, 11);
my $desc = substr($_, 12, 27);
my $income = substr($_, 40, 7);
my $expend = substr($_, 52, 7);
...
}
|
|
It's not really a barrel of laughs, is it? In fact, it's worse than it may seem; the
eagle-eyed may notice that the first field should only be 10 characters wide, and the error has
propagated right through the other numbers - which we've had to count by hand. So it's
error-prone as well as horribly unfriendly.
Or maybe we could use regular expressions:
while (<>) {
my($date, $desc, $income, $expend) =
m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|;
...
}
|
|
Urgh. Well, it's a bit better, but - well, would you want to maintain that?
Hey, isn't Perl supposed to make this sort of thing easy? Well, it does, if you use the right
tools. pack and unpack are designed to help you out when dealing with
fixed-width data like the above. Let's have a look at a solution with unpack:
while (<>) {
my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_);
...
}
|
|
That looks a bit nicer; but we've got to take apart that weird template. Where did I pull
that out of?
OK, let's have a look at some of our data again; in fact, we'll include the headers, and a
handy ruler so we can keep track of where we are.
1 2 3 4 5
1234567890123456789012345678901234567890123456789012345678
Date |Description | Income|Expenditure
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 235.00
|
|
From this, we can see that the date column stretches from column 1 to column 10 - ten
characters wide. The pack-ese for "character" is A, and ten
of them are A10. So if we just wanted to extract the dates, we could say this:
my($date) = unpack("A10", $_);
|
|
OK, what's next? Between the date and the description is a blank column; we want to skip over
that. The x template means "skip forward", so we want one of those. Next,
we have another batch of characters, from 12 to 38. That's 27 more characters, hence A27.
(Don't make the fencepost error - there are 27 characters between 12 and 38, not 26. Count 'em!)
Now we skip another character and pick up the next 7 characters:
my($date,$description,$income) = unpack("A10xA27xA7", $_);
|
|
Now comes the clever bit. Lines in our ledger which are just income and not expenditure might
end at column 46. Hence, we don't want to tell our unpack pattern that we need
to find another 12 characters; we'll just say "if there's anything left, take it". As
you might guess from regular expressions, that's what the * means: "use
everything remaining".
- Be warned, though, that unlike regular expressions, if the
unpack template
doesn't match the incoming data, Perl will scream and die.
Hence, putting it all together:
my($date,$description,$income,$expend) = unpack("A10xA27xA7A*", $_);
|
|
Now, that's our data parsed. I suppose what we might want to do now is total up our income
and expenditure, and add another line to the end of our ledger - in the same format - saying how
much we've brought in and how much we've spent:
while (<>) {
my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_);
$tot_income += $income;
$tot_expend += $expend;
}
$tot_income = sprintf("%.2f", $tot_income); # Get them into
$tot_expend = sprintf("%.2f", $tot_expend); # "financial" format
$date = POSIX::strftime("%m/%d/%Y", localtime);
# OK, let's go:
print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend);
|
|
Oh, hmm. That didn't quite work. Let's see what happened:
01/24/2001 Ahmed's Camel Emporium 1147.99
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 1235.00
03/23/2001Totals 1235.001172.98
|
|
OK, it's a start, but what happened to the spaces? We put x, didn't we?
Shouldn't it skip forward? Let's look at what perlfunc/pack says:
Urgh. No wonder. There's a big difference between "a null byte", character zero,
and "a space", character 32. Perl's put something between the date and the description
- but unfortunately, we can't see it!
What we actually need to do is expand the width of the fields. The A format pads
any non-existent characters with spaces, so we can use the additional spaces to line up our
fields, like this:
print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
|
|
(Note that you can put spaces in the template to make it more readable, but they don't
translate to spaces in the output.) Here's what we got this time:
01/24/2001 Ahmed's Camel Emporium 1147.99
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 1235.00
03/23/2001 Totals 1235.00 1172.98
|
|
That's a bit better, but we still have that last column which needs to be moved further over.
There's an easy way to fix this up: unfortunately, we can't get pack to
right-justify our fields, but we can get sprintf to do it:
$tot_income = sprintf("%.2f", $tot_income);
$tot_expend = sprintf("%12.2f", $tot_expend);
$date = POSIX::strftime("%m/%d/%Y", localtime);
print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend);
|
|
This time we get the right answer:
01/28/2001 Flea spray 24.99
01/29/2001 Camel rides to tourists 1235.00
03/23/2001 Totals 1235.00 1172.98
|
|
So that's how we consume and produce fixed-width data. Let's recap what we've seen of pack
and unpack so far:
- Use
pack to go from several pieces of data to one fixed-width version; use unpack
to turn a fixed-width-format string into several pieces of data.
- The pack format
A means "any character"; if you're packing
and you've run out of things to pack, pack will fill the rest up with spaces.
x means "skip a byte" when unpacking; when packing,
it means "introduce a null byte" - that's probably not what you mean if you're
dealing with plain text.
- You can follow the formats with numbers to say how many characters should be affected by
that format:
A12 means "take 12 characters"; x6 means
"skip 6 bytes" or "character 0, 6 times".
-
Instead of a number, you can use * to mean "consume everything else
left".
Warning: when packing multiple pieces of data, * only means
"consume all of the current piece of data". That's to say
packs all of $one into the first A* and then all of $two
into the second. This is a general principle: each format character corresponds to one piece
of data to be packed.
|
|