In Perl, how can I unpack to several variables?

只谈情不闲聊 提交于 2019-12-11 14:19:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!