Perl编程实例解析与代码实现

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;
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值