Perl: Removing NULL characters (0x00)

Alan Young alansyoungiii at gmail.com
Fri Feb 25 12:07:16 MST 2005


On Fri, 25 Feb 2005 11:22:07 -0700 (MST), David Smith
<DavidSmith at byu.net> wrote:
> I wrote a perl TCP/IP client program that talks to a server. The server
> sends me ASCII over the scoket, but it appends a NULL byte to every string
> (0x00), which I discovered with file redirection and a hex editor (it was
> invisible in the shell output). How can I prune this byte off of the
> string in Perl? I tried chomp, but it appears to only remove \r and \n. I
> also tried s/\s+$// but \s doesn't appear to match the 0x00 character.

chomp only removes \r and \n, chop removes the last character of the
string, but I don't know if it will do null bytes (don't see why it
wouldn't) but you don't want to do that anyway.  Also, a null byte
isn't white space, so \s wouldn't work.

You'd want to do

$in =~ s/\x0$//

or, if you want to be sure and trim off *all* null bytes from the end
of the string:

$in =~ s/\x0+$//

(technically, you should use \x00 but this shortcut works in this instance)
-- 
Alan



More information about the PLUG mailing list