Learning Perl: 2.7. Getting User Input

Previous Page
Next Page

 

2.7. Getting User Input

At this point, you're probably wondering how to get a value from the keyboard into a Perl program. Here's the simplest way: use the line-input operator, <STDIN>.[]

[] This is a line-input operator working on the filehandle STDIN, but we can't tell you about that until we get to filehandles (in Chapter 5).

Each time you use <STDIN> in a place where a scalar value is expected, Perl reads the next complete text line from standard input (up to the first newline) and uses that string as the value of <STDIN>. Standard input can mean many things; unless you do something uncommon, it means the keyboard of the user who invoked your program (probably you). If there's nothing waiting for <STDIN> to read (typically the case unless you type ahead a complete line), the Perl program will stop and wait for you to enter some characters followed by a newline (return).[*]

[*] To be honest, it's normally your system that waits for the input; Perl waits for your system. Though the details depend upon your system and its configuration, you can generally correct your mistyping with a backspace key before you press return since your system handles that, not Perl itself. If you need more control over the input, get the Term::ReadLine module from CPAN.

The string value of <STDIN> typically has a newline character on the end of it.[] So, you could do something like this:

[] The exception is if the standard input stream somehow runs out in the middle of a line. But that's not a proper text file, of course.

    $line = <STDIN>;
    if ($line eq "/n") {
      print "That was just a blank line!/n";
    } else {
      print "That line of input was: $line";
    }

In practice, you don't often want to keep the newline, so you need the chomp operator.

Previous Page
Next Page
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值