Home > perl, Programming > Perl study note 2: using unpack() to parse formatted data

Perl study note 2: using unpack() to parse formatted data

Example code: formatting 10-digit us phone numbers
#!/usr/bin/perl
# just for the purpose of illustrating the usage of unpack() function
# of course there are other ways such as regex, substring to get the
# same result
use strict;
use warnings;

my @numbers=(
'2223334444',
'2223456789',
'2228889999',
);

for my $n (@numbers) {
my ($area, $phone1, $phone2)=unpack('a3a3a4', $n);
print "$n => ($area)$phone1-$phone2\n";
}

Result:
2223334444 => (222)333-4444
2223456789 => (222)345-6789
2228889999 => (222)888-9999

This might not be the best solution to get this kind of task done but definitely it’s neater than using the substring method.

Advertisements
Categories: perl, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: