Unpacking a Perl string into a list
Archive - Originally posted on "The Horse's Mouth" - 2010-07-16 07:59:46 - Graham Ellis
Which should I use?
Whichever is most appropriate. If the data is always in the same columns numbers (character positions), then substr may be longer code but faster than the alternatives. And don't forget csv (comma separated variables) and XML modules too.
But rather than have many lines of substr, you may prefer to use unpack. Unpack lets you specify a list of destinations, and a number of columns and series of type conversions. So one line of unpack can replace many lines of substr and at no noticeable loss of efficiency. You can also use unpack if you have binary data held in your string.
I've added an example of unpack in use - [here] - from the current course. And I've also added in an example going the other way - taking a whole load of variables in a list and formatting them up into a string with pack
Perl's functions are documented [here]. The format converters for unpack (and pack) are documented [here]. We cover these functions - briefly - on our fundamental public Perl Programming Courses and in more detail if required on advanced and private courses.