Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with unpack

Status
Not open for further replies.

Bootstrap347

Programmer
Sep 20, 2008
2
I'm new to Perl and already seeing how powerful this language is. I need help understanding the following unpack command:
Code:
 @data = unpack(["","C*","n*","(H6)*",*N*"]->[$size], $table);

Here's what I know:

- unpack is unpacking $table into the array data
- unpack is using the template ["","C*","n*","(H6)*",*N*"]->[$size] to do so
- C refers to unsigned char values
- n refers to unsigned shorts
- H6 refers to high nybble hex strings
- N refers to unsigned longs
- * somehow is a repeat count

also

- $size = 3
- the resulting @data array, after execution, is 9 elements in size


The use of "", brackets (usually for array elements) around the template items and then the use of ->[$size] has lost me...

Hope you can help.



 
I'm far from being half an expert on pack/unpack, but a lot of the confusing part of this is just an odd use of a data structure.

Code:
 @data = unpack(["","C*","n*","(H6)*",*N*"]->[$size], $table);

The ["","C*","n*","(H6)*","*N*"] is an anonymous array reference. The ->[$size] is referring to an index out of that array. So if $size was 2, the effective code would be:

Code:
@data = unpack("n*", $table);

because element 2 of that anonymous arrayref was n*

You said that $size = 3, so here's what I can figure out:

Code:
# this is effectively what the code does when $size=3
$size = 3;
@data = unpack("(H6)*", $table);

What does $table look like before going through unpack and what does @data look like after? If you get any weird output like "HASH(0xff2cabd)" or whatnot when trying to print them to the terminal, use Data::Dumper, like

Code:
use Data::Dumper;
print Dumper($table);
...
print Dumper(\@data);

-------------
Cuvou.com | My personal homepage
Code:
perl -e '$|=$i=1;print" oo\n<|>\n_|_";x:sleep$|;print"\b",$i++%2?"/":"_";goto x;'
 
Thank you, Kirsle! We were unable to display the table until your tip to use Dumper, and the output confirms your explanation of the $size value selecting the index from the anonymous array to use for the unpack template.

Things seem so simple - once you understand them...

Perl rocks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top