What's the best way to read a fixed length record in Perl. I know to read a file like:
ABCDE 302
DEFGC 876
I can do
while (<FILE>) {
$key = substr($_, 0, 5);
$value = substr($_, 7, 3);
}
but isn't there a way to do this with read/unpack?
my($key, $value) = unpack "A5 A3"; # Original, but slightly dubious
We both need to check out the options at the unpack manual page (and, more particularly, the pack manual page).
Since the A pack operator removes trailing blanks, your example can be encoded as:
my($key, $value) = unpack "A6A3";
Alternatively (this is Perl, so TMTOWTDI):
my($key, $blank, $value) = unpack "A5A1A3";
The 1 is optional but systematic and symmetric. One advantage of this is that you can validate that $blank eq " "
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With