繁体   English   中英

限制用户在perl中仅输入1/2/3作为输入

[英]Restricting user to enter only 1/2/3 as input in perl

以编程方式读取1/2/3作为Perl中一个参数的输入的最简单方法是什么?

UPDATE

你可以试试这段代码:

do {$i = <>} while ($i !~ /^[123]$/);
print $i;

此代码从stdin读取到变量$ i,直到输入值为1/2/3。然后打印它。

这肯定不是最简单的方式,但是,它是相当简单和直接的,它的工作原理。

码:

$ cat test.pl 
#!/usr/bin/perl
use strict;
use warnings;
my $input=$ARGV[0];
print $input."\n" if $input =~ /^1$|^2$|^3$/;

输出:

$ perl test.pl 1
1
$ perl test.pl 2
2
$ perl test.pl 3
3
$ perl test.pl 12
$ perl test.pl 21
$ perl test.pl 13
$ perl test.pl 31
$ perl test.pl 4
$ perl test.pl 5
$ perl test.pl 11
$ perl test.pl 22
$ perl test.pl 33
$ 

您可以进一步自定义此代码以确保输入是必需的,否则脚本应打印脚本或类似内容的使用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM