[Chicago-talk] Reading & writing variable length packed

imran javaid imranjj at gmail.com
Tue Mar 17 04:22:26 PDT 2009


I knew I had used this technique before. I just didn't "read" the
"read" manpage properly while typing this code up.

On Mon, Mar 16, 2009 at 10:46 PM, Jay Strauss <me at heyjay.com> wrote:
> On Mon, Mar 16, 2009 at 1:52 PM, Jay Strauss <me at heyjay.com> wrote:
>> On Mon, Mar 16, 2009 at 9:30 AM, imran javaid <imranjj at gmail.com> wrote:
>>> This reminds me of a script I once wrote long ago to read a variable
>>> length file on a nine track tape.
>>> Here is a somewhat straight forward way to do it (did not test it and
>>> i am skipping some of the error checking on the return from read):
>>>
>>> open my $FILE, "<", $filename or die "Couldn't open file $filename: $!\n";
>>> my $buf;
>>> my $loc = 0;
>>> while(read($FILE, $buf, 2, $loc)) {
>>>  $loc += 2;
>>>  my $linenum = unpack("v", $buf);
>>>  my $ret = read($FILE, $buf, 1, $loc);
>>>  die if $ret != 1;
>>>  $loc++;
>>>  my $length = unpack("C", $buf);
>>>  if ($length == 255) {
>>>    $ret = read($FILE, $buf, 2, $loc);
>>>    die if $ret != 2;
>>>    $loc += 2;
>>>    $length = unpack("v", $buf);
>>>  }
>>>  $ret = read($FILE, $buf, $length, $loc);
>>>  die if $ret != $length;
>>>  print "LineNum: $linenum, Length: $length, Data: $buf\n";
>>> }
>>
>> Hi Imran,
>>
>> Thanks for the response.  I've done something sort of similar.  I'm
>> running into a problem now when I write the file.  I can't figure out
>> why my output file diffs from my orig.
>>
>> I'll try yours and see if I get different results.
>>
>> Jay
>>
>
> Yep, I get different results.  I never used "read" before, and it
> doesn't work like I was thinking or like you were thinking either.
> The offset isn't the offset into the file handle, its the offset into
> the target scalar.  Took me a long time to figure that error out :)
>
> Jay
> _______________________________________________
> Chicago-talk mailing list
> Chicago-talk at pm.org
> http://mail.pm.org/mailman/listinfo/chicago-talk
>


More information about the Chicago-talk mailing list