27、编写一个使用 DateTime 的 Perl 程序,计算当前时间与在命令行输入的年、月、日所代表日期之间的时间间隔,并以“X 年 X 个月 X 天”的格式输出结果。例如,运行程序时输入 perl duration.pl 1960 9 30 ,程序应输出类似“50 年 8 个月 20 天”的结果。
以下是实现该功能的程序:
#!/usr/bin/perl
use DateTime;
my $t = localtime;
my $now = DateTime->new(
year => $t[5] + 1900,
month => $t[4] + 1,
day => $t[3],
);
my $then = DateTime->new(
year => $ARGV[0],
month => $ARGV[1],
day => $ARGV[2],
);
my $duration = $now - $then;
my @units = $duration->in_units(qw(years months days));
printf "%d years, %d months, and %d days\n", @units;
你可以将上述代码保存为 duration.pl ,然后在命令行中运行 perl duration.pl 1960 9 30 来计算指定日期与当前日期的时间间隔。
28、编写一个程序,它接受命令行上指定的文件列表,并报告每个文件是否可读、可写、可执行或不存在。(提示:编写一个函数,每次对一个文件进行所有文件测试可能会有所帮助。)对于使用 chmod 0 命令修改权限的文件,程序会报告什么?(也就是说,如果你使用的是 Unix 系统,可以使用命令 chmod 0 some_file 将该文件标记为不可读、不可写且不可执行。)在大多数 shell 中,使用星号作为参数表示当前目录中的所有普通文件。也就是说,你可以输入类似 ./ex12 - 2 * 的命令,一次性询问程序多个文件的属性。
以下是实现该功能的程序:
foreach my $file (@ARGV) {
my $attribs = &attributes($file);
print "'$file' $attribs.\n";
}
sub attributes {
my $file = shift @_;
return "does not exist" unless -e $file;
my @attrib;
push @attrib, "readable" if -r $file;
push @attrib, "writable" if -w $file;
push @attrib, "executable" if -x $file;
return "exists" unless @attrib;
return 'is ' . join " and ", @attrib;
}
对于使用 chmod 0 命令修改权限的文件,程序会报告该文件“exists”,因为该文件存在但不具备可读、可写、可执行的属性。
29、编写一个程序,识别命令行中指定的最旧文件,并报告其存在的天数。如果列表为空(即命令行中未提及任何文件),程序会怎样处理?
程序会立即报错,提示 No file names supplied! ,因为没有文件可供检查,也就不存在最旧的文件。
30、编写一个程序,使用堆叠的文件测试操作符列出命令行中指定的所有可读、可写且由你拥有的文件。
从 Perl 5.10 开始,可以按如下方式编写程序:
use 5.010;
foreach my $file (@ARGV) {
if (-o -r -w $file) {
print "$file 是可读、可写且由你拥有的文件\n";
}
}
如果使用 Perl 5.10 之前的版本,代码如下:
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 $file && -r _ && -o _);
}

最低0.47元/天 解锁文章
763

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



