2
votes

I am writing a Perl program that sends and receives messages from two sockets and acta as a switch. I have to modify the received messages received from one socket, prepend 3 bytes to the data, and finally send the modified messages to another socket. I adopt select()...sysread()...syswrite() mechanism to poll for messages between sockets. The received messages are stored in $buffer during modification.

Now I can use following way to get the received messages:

my $hexmsg = unpack("H*", $buffer);
my @msg = ( $hexmsg =~ m/../g );

then I can insert 3 bytes to @msg. However, I don't know how to pack the message in @msg into a scalar(such as $buffer) and send it to another socket by syswrite(). Can anybody help me? Thank you in advance!

BTW, are messages in $buffer binary?

2
Besides, I have tried my $shexmsg=join("",@msg); $buffer=pack("X",$shexmsg); where "X" denotes template of pack, such as "n*", "b*","u*". However, all failed... I don't know what to do... - boyang

2 Answers

3
votes

Yes, messages in $buffer are binary (if I'm guessing what you mean by that correctly). If your only reason for unpacking it into @msg is to insert the bytes, don't. Use substr instead, and just write out the changed $buffer. For instance:

substr( $buffer, 0, 0, "\x01\x02\x03" ); # insert 3 bytes at beginning.

If you are doing other things with @msg, you could continue to use that as well as doing the substr insert before writing it out, or you could use substr or pack or split or vec or a regex to parse out the pieces you need. You'd need to describe what you are doing to get more specific help.

1
votes

If you've used unpack to get the data from $buffer, have you tried using pack to put the data back in there?