in reply to Bad Char in string

I believe your problems stem from the while (my $a=substr $z,$g,1) { line. Since the substr can possibly resolve to "0", that is getting evaluated as false; and the while exits.

You probably want something like

my $a; while (defined($a=substr($z,$g,1))) {
Find a good discussion on the difference between "if val" and "if defined val".
But you say you are writing a Gnutella client? Well, the packetsize is well defined for each type. 23 bytes for the header, plus (whatever) for the payload. You should be able to use something like
my $buff; sysread($socket,$buff,23); my ($did,$payloadid,$ttl,$hops,$length)=unpack("a16CCCL",$buff); my $payload; sysread($socket,$payload,$length);

(no error checking in example).