When we got a lot of values to
unpack it's a easy task, since perl allows you to concatenate the templates and unpack then in one call.
But not so lucky when some of the values need list context.
Searching through perlmonks I founded
this thread which was almost what I needed, except it unpacks everything in scalar context, so I modified it a bit and here we are:
sub unpack2hash
{
my ($template, $source) = @_;
my $hash = {};
foreach(split / /,$template)
{
my ($temp,$type,$var) = split /:(.)/;
if($type eq '@')
{
my @r = unpack $temp, $source;
$hash->{$var} = \@r;
my $pack = pack $temp, @r;
substr $source, 0, length $pack, '';
}elsif($type eq '$')
{
my $r = unpack $temp, $source;
$hash->{$var} = $r;
my $pack = pack $temp, $r;
substr $source, 0, length $pack, '';
}
else{ die "need context type\n" }
}
return $hash;
}
the template syntax is a bit different, see the example:
my $h = unpack2hash(join(' ',(
'l:$songid',
'c8:@signature',
'l:$genre',
'f:$bpm',
's3:@level',
's:$unk',
'l12:@unk2',
'a24:$genres',
'l2:@unk3',
'a32:$title',
'a32:$subtitle',
'a32:$artist',
'a32:$noter',
'a32:$musicfile',
'l:$jpg',
'l3:@unk4',
'l4:@notepos'
)), $data);
each value is separated by whitespace, in the format
<template>:<context><key>
this way, the values with
@ will be unpacked in list context and the values with
$ will be unpacked in scalar context, and stored in the hash with its respective key.
UPDATE: I changed the line
$source =~ s/$pack//; to
substr $source, 0, length $pack, ''; because
$pack was being interpreted as a regex.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.