SF. SF. - 2 months ago 5
Perl Question

Can't grab value from subexpressions

I'm reading null-separated blocks of data from a socket; upon finding a null, the block read so far is handed for processing, and the buffer is truncated to whatever was left after the null (usually nothing).

do {
$in .= <$sock>
} while(!in =~ /^(.*?)\x00(.*)/) ;
print "A:[ $in, $block ]\n";
$block = $1;
$in = $2;
print "B:[ $in, $block ]";


Result:

A:[ {"hn":"ITtestKA","v":{"m":4,"u":4}}
, ]
B:[ , ]


Why can't I pick the data from the subexpressions
$1
,
$2
?

Answer

Another idea is to change the value $/ which determines how much will <$sock> read from $sock. So for example, if you do

local $/="\0"

then for that scope, <$sock> will read until the end of the next (null-separated) block.

Edit: If the input consists of null-separated blocks, it does not make sense to use <$sock> with $/ having its default value, because then you would be reading the input line by line. So I think there are 2 approaches:

  1. Set $/ to \0 and use <$sock> to read the next block.
  2. Read a fixed size chunk and then search for a null byte in it to extract the next block. In this scenario, you can either use <$sock> with $/ set to a reference of the chunk size (e.g. local $/=\4096), or use read/sysread. I would also use index/substr to search for the null and extract the chunk in that case.