perlmeditation
samurai
When playing around with PHP for web development, there was an interesting feature I thought might be neat for perl to look at possibly including that was in PHP. It involves unpacking data.<p />
For example, right now I do a lot of this:<p />
<code>
my @fields = qw/ name sex age salary sign /;
my $unpack_tpl = "A20 A1 A3 A8 A12";
my %data = ();
@data{ @fields } = unpack $unpack_tpl, $string;
# { name => "Ted", sex => "M" ... }
</code><p />
to get hashed access to fixed-length data I'm parsing. But a neat feature of PHP is that you can supply the "field names" so to speak in the template itself. For example, perl pseudocode:
<code>
my $unpack_tpl = "A20name A1sex A3age, A8salary, A12sign";
my %data = unpack2 $unpack_tpl, $string;
</code><p />
I believe the second <code>$unpack_tpl</code> variable is more obvious as to what its doing than the original qw// list + unpack template version.<p />
I think this "unpack2" function would easily be able to tell if we were trying to do the special hashed version (returning key=>val instead of just val) based on whether the field specification had trailing non-whitespace to be used as the keys.<p />
Granted, I'm not talking about replacing unpack or making it part of the language spec (although the speed from it being in C would be nice), I'm thinking about toying with creating a module that might be able to do this kind of unpacking.<p />
Before I get started, can anyone see any inherent flaws with this kind of data unpacking, or perhaps come up with a reason why this might be An Exremely Bad Idea®?
<p />
--<br />
perl: code of the [samurai]