曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 5555|回复: 0
打印 上一主题 下一主题

获取用户输入 <STDIN> 和 chomp 函数

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34397
跳转到指定楼层
楼主
发表于 2011-7-16 13:21:52 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
<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
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-7-4 08:17 , Processed in 0.082292 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表