Perl – In Perl, how can I unpack to several variables


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?

Best Solution

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;
Related Question