Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Perl中修改二进制标量的特定部分?_Perl_String_Binary - Fatal编程技术网

如何在Perl中修改二进制标量的特定部分?

如何在Perl中修改二进制标量的特定部分?,perl,string,binary,Perl,String,Binary,我采用select()、sysread()、syswrite()机制来处理套接字消息,其中消息在系统写入之前被sysread()放入$buffer(二进制) 现在我想更改消息的两个字节,这表示整个消息的长度。首先,我使用以下代码: my $msglen=substr($buffer,0,2); # Get the first two bytes my $declen=hex($msglen); $declen += 3; substr($buffer,0,2,$declen); # change

我采用select()、sysread()、syswrite()机制来处理套接字消息,其中消息在系统写入之前被sysread()放入$buffer(二进制)

现在我想更改消息的两个字节,这表示整个消息的长度。首先,我使用以下代码:

my $msglen=substr($buffer,0,2); # Get the first two bytes
my $declen=hex($msglen);
$declen += 3;
substr($buffer,0,2,$declen); # change the length
然而,它不是这样工作的。如果$declen的最终值为85,则修改后的$buffer将为“0x35 0x35 0x00 0x02…”。我在$buffer中插入数字,但最终得到了ASCII

我也试过这样做:

my $msglen=substr($buffer,0,2); # Get the first two bytes,binary
$msglen += 0b11; # Or $msglen += 3;
my $msgbody=substr($buffer,2); # Get the rest part of message, binary
$buffer=join("", $msglen, $msgbody); 
不幸的是,这种方法也失败了。结果是“0x33 0x 0x00 0x02…”我只是想知道为什么两个二进制标量不能合并成一个二进制标量


你能帮我吗?谢谢大家!

您不能在Perl中直接连接两个二进制缓冲区—您所要做的就是调用获取ASCII,然后连接它并调用它返回

my $msglen=substr($buffer,0,2); # Get the first two bytes
my $number = unpack("S",$msglen);
$number += 3;
my $number_bin = pack("S",$number);
substr($buffer,0,2,$number_bin); # change the length

未经测试,但我认为这是你试图做的。。。将包含两个字节的表示短int的字符串转换为实际的int对象,然后再转换回来。

我找到了另一种可行的方法——使用vec

vec($buffer, 0, 16) += 3;

你是对的!我已经被这个问题折磨了很多天了!非常感谢你!连接二进制字符串没有问题,但必须连接正确的数据。