Perl文件与信号处理编程示例

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";
}

代码说明:

  1. 参数检查 :程序首先检查是否有命令行参数传递。如果没有,程序会终止并输出错误信息。
  2. 遍历文件 :使用 foreach 循环遍历每个命令行参数(文件)。
  3. 文件检查 :对于每个文件,程序使用文件测试操作符来检查文件的属性。如果文件存在,会进一步检查其是否可读、可写和可执行。如果文件不存在,会将 does not exist 添加到属性列表中。
  4. 结果输出 :根据属性列表生成结果字符串,并将其与文件名一起输出。

使用方法:

将上述代码保存为一个 .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;
}

代码解释:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值