24、修改一个程序,使其在运行过程中打印额外的调试信息,比如它选择的秘密数字。进行修改,以便可以关闭此功能,并且在关闭时程序不会发出警告。如果你使用的是 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;
25、使用DateTime编写一个Perl程序,计算当前时间与在命令行输入的年、月、日所表示的日期之间的时间间隔,示例:$ 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 1960 9 30 即可计算当前时间与1960年9月30日之间的时间间隔。
26、编写一个程序,使用堆叠文件测试操作符列出命令行中指定的所有可读、可写且归当前用户所有的文件。
在 Perl 5.10 及以后版本中,可使用如下代码实现:
use 5.010;
die "No files specified!
" unless @ARGV;
foreach my $file ( @ARGV ) {
say "$file is readable, writable and owned by me" if( -w -r -o $file );
}
在这个程序中,首先检查命令行是否指定了文件,如果没有则终止程序。然后遍历命令行中指定的每个文件,使用堆叠文件测试操作符 -w -r -o 来检查文件是否可写、可读且归当前用户所有,如果满足条件则输出该文件的信息。
27、编写一个程序,向用户询问一个目录名,然后切换到该目录。如果用户输入的行只有空白字符,则默认切换到其主目录。切换后,按字母顺序列出普通目录内容(不包括名称以点开头的项目)。(提示:使用目录句柄还是通配符会更容易实现?)如果目录切换不成功,只需提醒用户,不要尝试显示内容。
以下是实现该功能的程序:
print 'Which directory? (Default is your home directory) ';
chomp(my $dir = <STDIN>);
if ($dir =~ /\A\s*\Z/) {
chdir or die "Can't chdir to your home directory: $!";
} else {
chdir $dir or die "Can't chdir to '$dir': $!";
}
opendir DOT, "." or die "Can't opendir dot: $!";
foreach (sort readdir DOT) {
next if /\A\./;
print "$_\n";
}
解释:程序首先提示用户输入目录名,对输入进行处理。若输入为空则切换到主目录,否则切换到用户指定目录。切换成功后,打开当前目录句柄,读取目录内容,排序并过滤掉以点开头的文件,最后输出剩余文件。使用目录句柄实现该功能更合适,因为它能更好地处理当前目录的读取和过滤。
28、编写一个程序,其功能类似于 rm 命令,用于删除命令行中指定的任何文件(无需处理 rm 的任何选项)。
在Perl中,可以使用 unlink 操作符来实现此功能。示例代码如下:

最低0.47元/天 解锁文章
450

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



