曲径通幽论坛

标题: 获取用户输入 <STDIN> 和 chomp 函数 [打印本页]

作者: beyes    时间: 2011-7-16 13:21
标题: 获取用户输入 &lt;STDIN&gt; 和 chomp 函数
<STDIN> 操作符用来从标准输入读进一行文字(直到换行符为止)。
chomp 函数可以用来去掉行末的换行符。

测试代码
[code=perl]#!/usr/bin/perl

print "Please input a string for print: ";

$str = <STDIN>;

if ($str eq "\n") {
    print "You input a blank line!\n";
} else {
    print "You input: $str";
}

chomp ($str);
print "$str";[/mw_shl_code]
运行输出:
$ ./input.pl
Please input a string for print: hello perl
You input: hello perl
hello perl
需要注意的是,chomp 函数的书写可以有两种形式:
1. chomp($str);
2. chomp $str;
对于要处理的变量 $str,用括号括起来和不用括号效果一样。

对于上面的情况,chomp 有更简洁的处理方式:
chomp($str = <STDIN>);

下面这个例子将读入的字符串存放到数组中:
[code=perl]#!/usr/bin/perl

@lines = <STDIN>;

foreach (@lines) {
        print "$_";
}[/mw_shl_code]
运行输出:
# ./context.pl
abc
def
hij              #输完该行后输入 ctrl + d 表示结束输入
abc
def
hij
上面每读入的一行都会作为数组中的一个元素。
如果希望读入的几行数据不需要换行,那么可以结合 chomp 来修改上面的代码为:
[code=perl]#!/usr/bin/perl

chomp (@lines = <STDIN>);

foreach (@lines) {
        print "$_";
}[/mw_shl_code]
运行输出:
./context.pl
hello
world
helloworld





欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2