1、提示输入一些文本并使用.chars方法获取输入文本的字符数量
my $string = prompt 'Enter a string: ';
put 'There are ', $string.chars, ' characters';
2、编写代码,实现查找用户输入的字符串中是否存在子字符串 ‘Hamad’,并给出不区分大小写的查找实现方式。
以下是实现该功能的代码:
loop {
my $string = prompt 'Enter a string: ';
last if $string.chars == 0;
put 'Found Hamad!' if $string.contains: 'Hamad';
}
若要实现不区分大小写的查找,可以将字符串和子字符串都转换为小写:
loop {
my $string = prompt('Enter a string: ').lc;
last if $string.chars == 0;
put 'Found Hamad!' if $string.contains: 'Hamad'.lc;
}
3、编写一个简单的程序,接受两个数字作为输入,并计算它们的和、差、积和商。
以下是一个简单的Perl 6程序示例:
my $first = prompt( 'First number: ' );
my $second = prompt( 'Second number: ' );
if val($first) ~~ Numeric and val($second) ~~ Numeric {
put 'Sum is ', $first + $second;
put 'Difference is ', $first - $second;
put 'Product is ', $first * $second;
put 'Quotient is ', $first / $second;
} else {
put 'One of the values isn't numeric.';
}
4、编写程序实现以下要求:首先编写一个程序,从用户处获取两个字符串输入,将其视为可能的数字输入。在 if 条件中,使用 val 检查每个字符串是否可以转换为数字。若两个字符串都能转换为数字,则计算并输出它们的和、差、积、商;若有一个不能转换为数字,则输出提示信息。接着,编写另一个程序,同样从用户处获取两个字符串输入,检查每个字符串是否可以转换为数字,程序要有三条路径,分别指出第一个字符串有问题、第二个字符串有问题或者两个字符串都没问题。
两条路径的代码:
my $first = prompt( 'First number: ' );
my $second = prompt( 'Second number: ' );
if val($first) ~~ Numeric and val($second) ~~ Numeric {
put 'Sum is ', $first + $second;
put 'Difference is ', $first - $second;
put 'Product is ', $first * $second;
put 'Quotient is ', $first / $second;
} else {
put 'One of the values isn't numeric.';
}
三条路径的代码:
my $first = prompt( 'First number: ' );
my $second = prompt( 'Second number: ' );
if val($first) !~~ Numeric {
put 'The first string is not numeric.'
} elsif val($second) !~~ Numeric {
put 'The second string is not numeric.'
} else {
put 'Both strings are numeric.'
}
5、Instead of giving multiple things to put, do it all inside the interpolated Str to handle the input and the number of characters
不要多次使用 put 输出,而是将所有内容放在插值字符串中,以处理输入和字符数量。
6、使用条件运算符根据操作系统选择命令,然后将其插入到 qqx 中。同时,展示直接运行 shell 字符串的另一种方法。
使用条件运算符选择命令并插入到 qqx 中的示例:
my $command = $*DISTRO.is-win ?? 'C:\Windows\System32\hostname.exe' !! '/bin/hostname';
print qqx/$command/;
直接运行 shell 字符串的另一种方法:
print do if $*DISTRO.is-win {
qx/C:\Windows\System32\hostname.exe/
} else {
qx|/bin/hostname|
}

最低0.47元/天 解锁文章

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



