Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read fixed-length records in Perl?

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?

like image 629
David Nehme Avatar asked Jan 02 '09 16:01

David Nehme


1 Answers

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 " ".

like image 198
Jonathan Leffler Avatar answered Oct 29 '22 06:10

Jonathan Leffler