问题
I have a struct wich contains:
struct mystruct{
int id[10];
char text[40];
unsigned short int len;
};
And I'm trying to unpack it in a single line, something like this:
my(@ids,$text,$length) = unpack("N10C40n",$buff) ;
But everything is going to the first array(@ids), i've tried templates as "N10 C40 n
" and "(N10)(C40)(n)
"
So, either this can't be done or I'm not using the proper template string.
Note: I'm using big endian data.
Any hints?
回答1:
In list assignment the first array or hash will eat everything (how would it know where to stop?). Try this instead:
my @unpacked = unpack "N10Z40n", $buff;
my @ids = @unpacked[0 .. 9];
my ($text, $length) = @unpacked[10, 11];
you could also say
my @ids;
(@ids[0 .. 9], my ($text, $length)) = unpack "N10Z40n", $buff;
回答2:
If the order of the @ids
does not matter:
my ($length, $text, @ids) = reverse unpack("N10C40n",$buff) ;
来源:https://stackoverflow.com/questions/1165099/in-perl-how-can-i-unpack-to-several-variables