96、编写一个程序来处理作为命令行参数传递的文件。检查文件是否存在、是否可读、是否可写以及是否可执行,并报告结果。
#!/usr/bin/perl
use strict;
use warnings;
# 检查是否有命令行参数
if (!@ARGV) {
die "No files specified on the command line!";
}
# 遍历每个命令行参数(文件)
foreach my $file (@ARGV) {
my @attributes;
# 检查文件是否存在
if (-e $file) {
push @attributes, "exists";
# 检查文件是否可读
if (-r $file) {
push @attributes, "readable";
}
# 检查文件是否可写
if (-w $file) {
push @attributes, "writable";
}
# 检查文件是否可执行
if (-x $file) {
push @attributes, "executable";
}
} else {
push @attributes, "does not exist";
}
my $result = @attributes > 1 ? 'is ' . join(" and ", @attributes) : $attributes[0];
print "$file $result\n";
}
代码说明:
- 参数检查 :程序首先检查是否有命令行参数传递。如果没有,程序会终止并输出错误信息。
- 遍历文件 :使用
foreach循环遍历每个命令行参数(文件)。 - 文件检查 :对于每个文件,程序使用文件测试操作符来检查文件的属性。如果文件存在,会进一步检查其是否可读、可写和可执行。如果文件不存在,会将
does not exist添加到属性列表中。 - 结果输出 :根据属性列表生成结果字符串,并将其与文件名一起输出。
使用方法:
将上述代码保存为一个 .pl 文件,例如 file_check.pl ,然后在命令行中运行:
perl file_check.pl file1.txt file2.sh
这将检查 file1.txt 和 file2.sh 的属性并输出结果。
97、使用 given 和智能匹配来检查作为命令行参数传递的数字是否为有效数字、是否为质数或是否能被其他数字整除。实现一个 divisors 子例程。
以下是实现该功能的代码:
use 5.010;
say "Checking the number <$ARGV[0]>";
given( $ARGV[0] ) {
when( ! /\A\d+\Z/ ) {
say "Not a number!"
}
my @divisors = divisors( $_ );
my @empty;
when( @divisors ~~ @empty ) {
say "Number is prime"
}
default {
say "$_ is divisible by @divisors"
}
}
sub divisors {
my $number = shift;
my @divisors = ();
foreach my $divisor ( 2 .. $number/2 ) {
push @divisors, $divisor unless $number % $divisor;
}
return @divisors;
}


427

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



