88、要求用户输入一个字符串和一个子字符串,找出子字符串在字符串中的所有位置并打印出来,该如何编写代码?
可以使用以下代码实现:
print "Please enter a string: ";
chomp(my $string = <STDIN>);
print "Please enter a substring: ";
chomp(my $sub = <STDIN>);
my @places;
for (my $pos = -1; ; ) {
$pos = index($string, $sub, $pos + 1);
last if $pos == -1;
push @places, $pos;
}
print "Locations of '$sub' in '$string' were: @places\n";
也可以使用 while 循环实现相同功能:
my $pos = -1;
while (1) {
$pos = index($string, $sub, $pos + 1);
last if $pos == -1;
push @places, $pos;
}
89、编写一个猜数字程序,不使用智能匹配,但使用 given 。程序要求用户猜一个1到100之间的数字。
以下是一种重写猜数字程序的方式,不使用智能匹配,但使用 given :
use 5.010;
my $Verbose = $ENV{VERBOSE} // 1;
my $secret = int(1 + rand 100);
print "Don't tell anyone, but the secret number is $secret.\n" if $Verbose;
LOOP: {
print "Please enter a guess from 1 to 100: ";
chomp(my $guess = <STDIN>);
my $found_it = 0;
90、使用 given 重写猜数字程序(不一定要使用智能匹配),猜数字程序为:程序随机生成一个 1 到 100 之间的整数,用户输入猜测的数字,程序根据用户输入给出相应提示,直到用户猜对为止。
以下是一种重写猜数字程序的方式,不使用智能匹配,但使用了 given :
use 5.010;
my $Verbose = $ENV{VERBOSE} // 1;
my $secret = int(1 + rand 100);
print "Don't tell anyone, but the secret number is $secret.\n" if $Verbose;
LOOP: {
print "Please enter a guess from 1 to 100: ";
chomp(my $guess = <STDIN>);
my $found_it = 0;

最低0.47元/天 解锁文章
715

被折叠的 条评论
为什么被折叠?



