Main Content

Unpacking a Perl string into a list

Archive - Originally posted on "The Horse's Mouth" - 2010-07-16 07:59:46 - Graham Ellis

In Perl, you can extract data from a string in a lot of different ways. You can split the string if you want to use a uniform separator, you can use a regular expression if you want to grab out bits that match a pattern, and you can use substr to extract data based on specific character positions.

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.