📜  珀尔 |标量和列表上下文中的 STDIN

📅  最后修改于: 2022-05-13 01:54:48.550000             🧑  作者: Mango

珀尔 |标量和列表上下文中的 STDIN

Perl 中的 STDIN 用于从键盘获取输入,除非用户重新定义了它的工作。

标量上下文中的标准输入


Perl 中使用了为了从键盘或运算符获取输入。该运算符读取通过键盘输入的行以及与我们在输入后按下的 ENTER 对应的字符。

例子:

# Asking user for Input
print "What is your age?\n";
  
# Getting an age from the user
$age = ;
  
# Removes new line from the input
chomp $age;
  
# Printing the value entered by user
print "Your age is ", $age;

输出:

所以 $age 包含用户给出的输入以及字符。为了删除新行,使用 chomp函数从字符串的末尾删除“\n”。

列表上下文中的 STDIN


当 STDIN 与列表上下文一起使用时,它需要多个值作为键盘的输入。按 ENTER 指示列表中的各个元素。为了指示输入的结束,在 Linux 系统中按 Ctrl-D,而在 Windows 系统中按 Ctrl-Z。
下面的示例显示了在列表上下文中使用 STDIN。
例子:

# Get a city name from the user 
print "Enter the cities you have visited last year... ";
print "-D to Terminate \n";
@city = ;
  
# Removes new line appended at 
# the end of every input
chomp @city;
  
# Print the city names
print "\nCities visited by you are: \n@city ";

输出:

以下是上述程序的工作原理:
第 1 步:从用户那里获取列表输入,以 ENTER 分隔。
第 2 步:当按下 Ctrl-D 时,它表示输入的结束,因此,Perl 将所有内容分配给 @city 数组。
第 3 步:使用 chomp函数从所有输入中删除新行。
第 4 步:打印输入中给出的城市名称。