Bdfy
Bdfy

Reputation: 24621

How to add null-character to string in Perl?

I want to create string in perl with length, for example 7, but "visible" contents, for example "a".

my $test = ...;

print $test result: "a" print length($test) result: 7

Upvotes: 5

Views: 10240

Answers (3)

A usage example:

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

require 'syscall.ph';

my $path = '/root/target';
my $buf = "\0"x512; # $buf (pointer) must be large enough to receive data

# See statf(2) on Linux
syscall(&SYS_statfs, $path, $buf) == 0 or die($!);

my @st = unpack 'L7', $buf;

print Dumper(\@st);

1;

Upvotes: 0

Knut Haugen
Knut Haugen

Reputation: 1972

You add null characters to the string. Why you want to this is beyond me, but how you do it is shown below.

{ow-loopkin:tmp:->perl
$string = "e\0\0\0\0";
print length $string;
[ctrl+d]
5
{ow-loopkin:tmp:->

You can also use pack() to pad it with nulls:

ow-loopkin:tmp:->perl
$string = pack("Z6", 42);
print length $string;
[ctrl+d]
6
{ow-loopkin:tmp:->

Upvotes: 14

Alex Reynolds
Alex Reynolds

Reputation: 96937

See the pack function, perhaps.

Upvotes: -1

Related Questions