On 11/09/2006 10:24 PM, R. Wajda wrote:
Hi all,

is there any way how to simplify this function:

sub h_escapes {
my ($index, $char, $output);

for($index=0; $index<length($_[0]); $index++) {
$char = ord(substr($_[0], $index, 1));

if($char < 0x20 || $char > 0x7f) {
$output = $output . sprintf("\\x%02x", $char);
} else {
$output = $output . substr($_[0], $index, 1);
}
}

return $output;
}

It converts 'non-printable' characters in string to ansi hex escapes (\xxx)
and returns new string. Maybe there is some standard function for this
purpose, which I missed. Or maybe with regular expression it's possible to
do it as one-liner.

Any hints?

Regards,
R. Wajda


Off the top of my head, I can think of this:

sub h_escapes {
        local $_ = shift();
        s/([^[:print:]])/sprintf("\\x%02x", ord($1))/ge;
        $_;
}

That's untested code. Analyze it before use.

You could also use (possibly after installing it from CPAN) String::Escape.

http://search.cpan.org/





--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to