1、创建一个包含值 Andrew、Andy 和 Kaufman 的数组,并编写一个程序来输出 Andrew “Andy” Kaufman。
以下是使用 Perl 实现的代码:
use strict;
use warnings;
my @array = ('Andrew', 'Andy', 'Kaufman');
print $array[0]. ' “'. $array[1]. '” '. $array[2]. "\n";
上述代码首先创建了一个包含指定值的数组,然后通过数组索引取出元素并拼接成所需的字符串进行输出。
2、创建一个哈希表,键为水果名称,值为它们的常见颜色,然后将每个键/值对作为单独的一行打印出来,格式类似于“香蕉是黄色的”。
以下代码可以实现该功能:
use strict;
use warnings;
use diagnostics;
my %color_for = (
bananas => 'yellow',
apples => 'red',
oranges => 'orange',
);
for my $fruit (keys %color_for) {
my $color = $color_for{$fruit};
print "$fruit are $color\n";
}
3、在$second、$fourth和$sixth这些变量中,哪些变量的求值结果为真?如何让$fourth的求值结果为假?
在 Perl 里,非空字符串会被视为真。
-
$second是一个空格字符串 -
$fourth是字符串'0.0' -
$sixth是字符串'false'
它们都是非空字符串,求值结果都为真。
若要让 $fourth 求值为假,可将其赋值为空字符串或数字 0 ,例如:
$fourth = ''; # 赋值为空字符串
或者
$fourth = 0; # 赋值为数字 0
4、给定华氏温度数组@fahrenheit (0, 32, 65, 80, 212),创建对应的摄氏温度数组@celsius。
要将华氏温度转换为摄氏温度,需先减去32,再乘以5/9。以下是创建 @celsius 数组的代码:
my @fahrenheit = ( 0, 32, 65, 80, 212 );
my @celsius = map { ( $_ - 32 ) * 5 / 9 } @fahrenheit;
5、给定数组 @ids 为 (AAA bbb Ccc ddD EEE),将 @ids 数组元素全部转换为大写来创建数组 @upper。
可使用如下 Perl 代码:
my @ids = qw(AAA bbb Ccc ddD EEE);
my @upper = map { uc } @ids;
上述代码使用 map 函数和 uc 函数将 @ids 数组元素全部转换为大写后赋值给 @upper 数组。
6、如何创建一个哈希,键为水果名称,值为它们的正常颜色,并将每个键值对作为单独的一行打印出来,格式类似于“bananas are yellow”?
可以使用以下代码实现:
use strict;
use warnings;
use diagnostics;
my %color_for = (
bananas => 'yellow',
apples => 'red',
oranges => 'orange',
);
for my $fruit (keys %color_for) {
my $color = $color_for{$fruit};
print "$fruit are $color\n";
}
7、判断 $second, $fourth, 和 $sixth 是否都为真。其中 $fourth 是字符串 ‘0.0’,如何让它为假以及如何判断这三个变量是否都为真?
在 Perl 里,字符串形式的 '0.0' 会被视作假值。要判断 $second 、 $fourth 和 $sixth 是否都为真,可使用逻辑与运算符 && 。示例代码如下:
if ($second && $fourth && $sixth) {
print '都为真';
} else {
print '并非都为真';
}
由于 $fourth 是 '0.0' 字符串,本身就会被当作假值处理。
8、如何创建 @celsius 数组,已知 @fahrenheit 数组为 ( 0, 32, 65, 80, 212 ) ?
要创建


693

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



