Passing Binary Data Between Chilkat and Perl

This example explains how to pass binary data between Chilkat and Perl.


use chilkat();

$bd = new chilkat::CkBinData();

# Create a binary string in Perl.
my $binary_string = pack("C*", 0, 1, 2, 3, 4);

# Copy the bytes to the CkBinData object.
$bd->AppendData($binary_string,length($binary_string));
    
# View the contents of bd in hexadecimal format.
# Output: 0001020304
print $bd->getEncoded("hex") . "\r\n";
    
# Append a few more bytes
$bd->AppendEncoded("05060708","hex");
    
# Call GetData to copy the bytes to a new binary string
$binary_string = $bd->GetData();
    
# Print each byte value
# Print each byte using ord()
for (my $i = 0; $i < length($binary_string); $i++) {
    print ord(substr($binary_string, $i, 1)) . "\n";
}

print "----\n";
 
# Output is:
# 0
# 1
# 2
# ...
# 8
    
# You can get a range of bytes by calling GetDataChunk
# GetDataChunk has 0-based indexing.  The 1st byte is at index 0.
$binary_string = $bd->GetDataChunk(2,4);
for (my $i = 0; $i < length($binary_string); $i++) {
    print ord(substr($binary_string, $i, 1)) . "\n";
}
    
# Output is:
# 2
# 3
# 4
# 5