Beau E. Cox wrote:
> I really thought I understood pack/unpack,
> but this has me stumped. I can't find anything to
> explain the operation of the following script
> in the documentation:
>
> use strict;
> use warnings;
>
> my $buffer = pack( "NN", 22, 0 );
> printf "buffer length = %s\n", length $buffer;
> print "buffer ",
> join( " ", map { sprintf "%02x", ord( $_ ) } split "", $buffer ),
> "\n";
> my( $len1, $len2 ) = unpack "NN", $buffer;
> printf "len1 = %s len2 = %s\n",
> $len1 || 'undef', $len2 || 'undef';
>
> which gives this result:
>
> $ perl tpack.pl
> buffer length = 8
> buffer 00 00 00 16 00 00 00 00
> len1 = 22 len2 = undef
>
> Why is len2 undefined instead of 0? Any ideas?
That test does not show len2 is undefined, you are just seeing that the
expression
$len2 || 'undef'
evaluates to the string 'undef'.
That's because $len2 is the false value 0, and so || evaluates the right
operand, which is the string 'undef'. Since the string 'undef' is true
in boolean context that's what the expression returns. In particular,
you are not even getting the special scalar value undef, you are getting
a string that happens to contain the characters 'u', 'n', 'd', 'e', and 'f'.
Your understanding of pack/unpack is OK:
% perl -wle '$x = pack "NN", 22, 0; print for unpack "NN", $x'
22
0
The lesson learned here is that tests of that kind should be as minimal
as possible.
-- fxn
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>