26、编写一个 Perl 程序,程序会生成一个 1 到 100 之间的随机整数作为秘密数字。要求程序在运行过程中可以打印额外的调试信息,例如它选择的秘密数字。并且可以关闭此功能,当关闭时程序不会发出警告。如果你使用的是 Perl 5.10 或更高版本,请使用 // 运算符。否则,请使用条件运算符。
下面是给定的【文本内容】:
使用 Perl 5.10 及以后版本:
```perl
use 5.010;
my $Debug = $ENV{DEBUG} // 1;
my $secret = int(1 + rand 100);
print "Don't tell anyone, but the secret number is $secret.\n" if $Debug;
不使用 Perl 5.10 新特性:
my $Debug = defined $ENV{DEBUG} ? $ENV{DEBUG} : 1;
my $secret = int(1 + rand 100);
print "Don't tell anyone, but the secret number is $secret.\n" if $Debug;
27、编写一个使用 DateTime 模块的程序,计算当前时间与在命令行输入的年、月、日所表示的日期之间的时间间隔,例如执行 perl duration.pl 1960 9 30 会输出 50 years, 8 months, and 20 days 。
以下是实现该功能的 Perl 代码:
use DateTime;
# 获取当前时间
my $now = DateTime->now;
# 从命令行获取输入的日期
my $then = DateTime->new(
year => $ARGV[0],
month => $ARGV[1],
day => $ARGV[2],
);
# 检查输入的日期是否在未来
if ($now < $then) {
die "You entered a date in the future!\n";
}
# 计算时间间隔
my $duration = $now - $then;
# 获取年、月、日的时间间隔
my @units = $duration->in_units(qw(year month day));
# 输出结果
printf "%d years, %d months, and %d days\n", @units;
将上述代码保存为 duration.pl ,然后在命令行运行 perl duration.pl 年 月 日 即可计算时间间隔。
28、编写一个程序,使用堆叠文件测试运算符列出命令行中指定的所有可读、可写且归当前用户所有的文件。
在 Perl 5.10 及以后版本中,示例代码如下:
use 5.010;
print "Looking for my files that are readable and writable\n";
die "No files specified!\n" unless @ARGV;
foreach my $file ( @ARGV ) {
print "$file is readable and writable\n" if( -w -r -o $file );
}
该代码首先提示正在查找可读且可写的文件,接着检查命令行是否指定了文件,若未指定则终止程序。然后遍历命令行指定的每个文件,使用堆叠文件测试运算符 -w -r -o 检查文件是否可写、可读且归当前用户所有,若满足条件则打印文件名。
29、修改程序以包含所有文件,而不仅仅是不以点开头的文件。
若要修改程序以包含所有文件,可移除跳过点文件的代码:
- 在第一个程序里,移除
## now includes .*相关注释以及next if /A./;这行代码; - 在第二个程序中,去掉
next if /A./;这行代码; - 在第三个程序中,去掉
next if $name =~ /^./;这行代码。
这样程序就能包含所有文件,而不只是不以点开头的文件。
30、编写一个程序,其功能类似于 mv 命令,将第一个命令行参数指定的文件重命名为第二个命令行参数指定的名称。(无需处理 mv 命令的选项或额外参数。)要考虑目标参数可能是一个目录的情况;如果是目录,则在新目录中使用原文件的基本名称。
以下是实现该功能的 Perl 程序:
use File::Basename;
use File::Spec;
my ($source, $dest) = @ARGV;

最低0.47元/天 解锁文章
2158

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



