Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl array(@data) to variables($data)

Tags:

perl

I am doing socket programming. The data ($ data) received from the socket contains 4 bytes of length data + json data. I want to trim the length and only parse the json.

I have completed the code and it works fine. But I wonder if there is a more efficient way (algorithm).

Is there an efficient way to move arrays to variables in perl?

@tmpp = split(//,$data); #data = socket data

my $t1 = sprintf("%02x%02x%02x%02x",ord($tmpp[0]),ord($tmpp[1]),ord($tmpp[2]),ord($tmpp[3])); 
$t1 = hex($t1); #t1 = length 

my $json;
my @tmp = @tmpp[0..-1];
foreach(@tmp){ $json .= $_;}<br>
print $json;

Ok Print ; 
like image 734
SAnji Holic Avatar asked Aug 14 '26 03:08

SAnji Holic


1 Answers

This is a standard case for pack/unpack. The N/a template will unpack a string of length N (in network byte order):

my( $json ) = unpack 'N/a', $data;
print $json;
like image 164
Corion Avatar answered Aug 17 '26 10:08

Corion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!