SPUG: Re: unpack

Richard Anderson richard at richard-anderson.org
Fri Mar 15 00:55:28 CST 2002


Not 100% certain, but it looks like you forgot to account for the null
terminator on the string.  $len=length($alpha)-4; gives you the length of
the string + 1 for the null terminator.  Try $len=length($alpha)-5.

(Somewhat relevant aside: using hard-coded values for system-dependent
values like the length of a long is not very portable.  It's better to use a
variable for magic numbers like this, and document what it represents.  Even
better, have your C code calculate this with the sizeof operator, write it
to the data file and read this value for use by your Perl code.)

Cheers,
Richard
richard at richard-anderson.org
www.richard-anderson.org
www.raycosoft.com
----- Original Message -----
From: "Benjamin Franks" <benjamin at dzhan.com>
To: <spug-list at pm.org>
Sent: Thursday, March 14, 2002 4:45 PM
Subject: SPUG: unpack


> Thanks for all the responses recommending unpack().  Here's an example
> I'm trying:
>
> struct alpha {
>   char   *a;
>   long b;
> };
>
> Now let's say the byte-string equivalent is stored in a file.  I snag it
> into perl into $alpha;
>
> $len=length($alpha)-4;
>   ($a,$b) = unpack("a$len l",$alpha);
>
> I get the 4-byte long value correctly.  But the string for $a is
> garbled or empty.
>
> Any ideas,
> --Ben
>
>
>  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
>      POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
>       Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
>   Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
>  For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
>      Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org
>
>
>


 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org





More information about the spug-list mailing list