Perl读取行字符串,不带尾随换行符

时间:2014-08-26 18:51:47

标签: perl variables

非常新的perl并且已经停留了很长一段时间。

如果我将变量从READSTDIN更改为google.com,则表示google.com应该在线。如果我使用STDIN并输入google.com并打印$ host,则会打印google.com,但是在ping中它不起作用。

示例输出:

    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

代码:

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();

如果我将变量从READSTDIN更改为google.com,则表示google.com应该在线。如果我使用STDIN并输入google.com并打印$ host,它会打印google.com,但是在ping中它不起作用。我感谢任何能帮助我的人!

1 个答案:

答案 0 :(得分:1)

请注意输入中的换行符:

    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

您应该使用chomp从输入中删除换行符:

chomp( my $host = readline STDIN );

或更简单:

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