Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi

The following code is failing to react to the command "exit":
#!/usr/bin/perl use strict; use warnings; use IO::Socket; my $sock = new IO::Socket::INET ( LocalPort => '17071', Proto => 'tcp', Listen => 1, Reuse => 1, ); die "Could not create socket: $!\n" unless $sock; my $new_sock = $sock->accept(); while(<$new_sock>) { my $command = $_; chomp($command); $command = lc($command); if($command eq "exit") { print "EXITING"; } print $command,"\n"; } print "Closing Socket..."; close($sock); print "Soocket Closed";

The line with "eq" is failing. I'm on a linux system. Is there a better way to strip away junk that I can't see? How can I output a string variable so that I can see the hidden characters? In C, I would output each character as a hex number.

Thanks!

Replies are listed 'Best First'.
Re: Problem using chomp on linux
by moritz (Cardinal) on Mar 17, 2009 at 08:56 UTC
    use Data::Dumper; $Data::Dumper::Useqq = 1; ... print Dumper($command)

    If you want to remove all trailing white spaces (including carriage return), try $command =~ s/\s+\z//;

      Thanks!

      It seems I have a trailing byte storing the value 0x0d at the end of my strings after the chomp. This is the carriage return character. And it seems that s/\s+\z// removes this

        Be careful, when you use chomp; you need to be aware what it does.

        chomp removes the current input record separator from the string. This is the value stored in $/. On *nix systems this defaults to "\n". If you're reading stuff from the interwebs or from text files created on dos systems, then the end of the lines will likely be crlf or "\r\n". Using chomp will therefore remove the linefeed but not the carriage return, which is what you found.

        There are a number of solutions, but the easiest is probably to change the value of $/:

        local $/ = "\r\n";

        Remember the good advice in perlipc.

        update: fixed the link