Adam Black
Adam Black

Reputation: 11

Perl read line string without trailing newline

Very new to perl and have been stuck for quite awhile on this.

If I change the variable from READSTDIN to google.com, it says google.com is online as it should. If I use the STDIN and input google.com and print $host it prints google.com, however in the ping it doesn't work.

Sample output:

    perl perl.pl
What is the website that is offline or displaying an error?google.com
Warning: google.com
 appears to be down or icmp packets are blocked by their server

Code:

use strict;
use warnings;
use Net::Ping;

#optionally specify a timeout in seconds (Defaults to 5 if not set)
my $timeout = 10;

# Create a new ping object
my $p = Net::Ping->new("icmp");

#Domain variable
print "What is the website that is offline or displaying an error?";
my $host = readline STDIN;

# perform the ping
if ( $p->ping( $host, $timeout ) ) {
    print "Host $host is alive\n";
} else {
    print "Warning: $host appears to be down or icmp packets are blocked by their server\n";
}

# close our ping handle
$p->close();

If I change the variable from READSTDIN to google.com, it says google.com is online as it should. If I use the STDIN and input google.com and print $host it prints google.com, however in the ping it doesn't work. I appreciate anyone who can help me at all!

Upvotes: 1

Views: 3094

Answers (1)

Oesor
Oesor

Reputation: 6652

Note the newline in your input:

    perl perl.pl
What is the website that is offline or displaying an error?google.com
Warning: google.com <--- newline after google.com puts the rest of the output on the next line...
 appears to be down or icmp packets are blocked by their server

You should be using chomp to remove the newline from your input:

chomp( my $host = readline STDIN );

Or more simply:

chomp( my $host = <STDIN> );  # same thing as above

Upvotes: 1

Related Questions