On Dec 9, 2007 7:10 AM, Niu Kun <[EMAIL PROTECTED]> wrote:
snip
> My network protocol is like this:
> String length(4 bytes, big endian) plus the real string.
> For simple simulate purpose, I'll limit the string length to less than 256.
> So I've got one byte containing the length of the string.
> The other end is written in C++.
> I've got a solve method with sprintf.
> But I'd rather use a way more perlish.:)
snip

It sounds like you want something like

use Carp;

sub send_msg {
    my ($sock, $msg) = @_;
    use bytes;
    my $len = length $msg;
    no bytes;
    my $maxlen = 2**32-1;
    croak "$msg is too long (there is a $maxlen byte limit)" if $len > $maxlen;
    print $sock pack "Na*", $len, $msg;
}

if you are going to use the four byte big-endian length or

use Carp;

sub send_msg {
    my ($sock, $msg) = @_;
    use bytes;
    my $len = length $msg;
    no bytes;
    my $maxlen = 2**32-1;
    croak "$msg is too long (there is a $maxlen byte limit)" if $len > $maxlen;
    print $sock pack "Ca*", $len, $msg;
}

if you are going to use the one byte length.  It is important that you
use the bytes pragma.  As I said before, Perl strings are in UTF-8.
The length function returns the number of characters (not the number
of bytes) by default.  This behavior can be overridden with the bytes
pragma:

#!/usr/bin/perl

use warnings;
use strict;

my $msg = chr(0x263a);
my $length = length $msg;

use bytes;
my $bytes = length $msg;
no bytes;

print "$msg is $length character(s) long and $bytes byte(s) long\n";

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to