[comp.lang.perl] pack and unpack

rob@lighthouse.com (Rob Kedoin) (05/16/91)

I was trying to use pack for the first time today and I can't get the
following test program to do what I want:

--- cut here ---
#!/usr/bin/perl
# packTest.  Experiment with pack.
#
# Expected output was:
# foo
# bar
# baz
#
# Actual output is:
# f
# b
# b

$struct = pack("aaa", "foo", "bar", "baz");

($foo, $bar, $baz) = unpack("aaa", $struct);

print "$foo\n";
print "$bar\n";
print "$baz\n";
--- cut here ---

Does anyone know why I would only get the first character of the
string and how to fix this.  Just for reference, I'm running on a NeXT
computer using Perl:

"This is perl, version 4.0

$RCSfile: perl.c,v $$Revision: 4.0.1.1 $$Date: 91/04/11 17:49:05 $
Patch level: 3"

Thanks in advance,

Rob Kedoin		rob@lighthouse.com
Lighthouse Design, Ltd
6516 Western Avenue Chevy Chase, MD 20815

tchrist@convex.COM (Tom Christiansen) (05/18/91)

From the keyboard of rob@lighthouse.com (Rob Kedoin):
:I was trying to use pack for the first time today and I can't get the
:following test program to do what I want:
:
:--- cut here ---
:#!/usr/bin/perl
:# packTest.  Experiment with pack.
:#
:# Expected output was:
:# foo
:# bar
:# baz
:#
:# Actual output is:
:# f
:# b
:# b
:
:$struct = pack("aaa", "foo", "bar", "baz");
:
:($foo, $bar, $baz) = unpack("aaa", $struct);
:
:print "$foo\n";
:print "$bar\n";
:print "$baz\n";
:--- cut here ---
:
:Does anyone know why I would only get the first character of the
:string and how to fix this.  

An 'a' format is just one ascii character.  Structures tend to be fixed
format.  You need to specify how long each string is, or at most use a*
for the last one.

    $fmt = 'a10' x 3;
    $struct = pack("aaa", "foo", "bar", "baz");
    ($foo, $bar, $baz) = unpack("aaa", $struct);
    
This doesn't really buy you very much unless you're reading
fixed-format (and often binary) records.

--tom
--
Tom Christiansen		tchrist@convex.com	convex!tchrist
		"So much mail, so little time."