下午好,stackoverflow 的朋友们!
我被分配了以下任务,并想了解如何查看文件或目录是否存在。
"提示用户输入一个参数(注意这个脚本只接受一个参数,如果用户输入包含零个或多个参数,应该报告警告/错误),检查输入参数是文件名还是目录名。
1) 如果用户输入的是文件,当文件为空文件时退出,并打印文件的最后一行。
2)如果用户输入的是目录,则目录为空时退出,使用哈希表记录该目录内的文件名和这些文件的评估年龄(自上次评估文件以来的天数),找到目录中最旧的文件(基于修改时间),并打印该文件的绝对路径。”
在过去的 2 天里,我一直在寻找有关如何使用 File::Find 但不能使用的详细说明。下面是我的代码,我想用 File::Find 替换 -e $input 部分,因为使用 -e 文件运算符,我只能在当前目录中搜索,而不能在整个系统中搜索。我期待您的回复,并非常感谢您的宝贵时间。
#! /usr/bin/perl
# Assignment 9, check and read files and directories
use strict;
use warnings;
use Module1;
assnintro();
my @parameter;
my $input;
do { # This loop keeps calling pamcheck subroutine until the 1 param entered
# is a file in the directory, but I'd to expand the file test operator
# to all directories
$input = ();
@parameter = ();
pamcheck( \@parameter );
$input = $parameter[0];
if ( -e $input ) { } # Instead of simply checking current directory, I want to
# I want to see that the file exists in my system
else {
print color 'red';
print "The file or directory you entered, doesn't exist.\n";
print color 'reset';
}
} until ( -e $input );
if ( -d $input ) {
print "I am a directory.\n";
} else {
}
exit;
sub pamcheck { # This subroutine asks user to to enter a file or directory name
my ($parameter) = @_; # In the terminal, "parameters" are separated by space
my $elementcount; # Do elem ct. to make sure usr only entered 1 parameter
do {
@$parameter = ();
print "Enter one file or directory name: ";
@_ = split( /\s+/, <> ); # "Enter" key act as Ctrl D to avoid infinite
# param entry
push( @$parameter, @_ );
$elementcount = 0;
foreach (@_) {
$elementcount++;
}
if ( $elementcount != 1 ) { # Error msg if 1 param isn't entered
print color 'red';
print "Please enter only ONE parameter.\n";
print color 'reset';
} else {
}
} until ( $elementcount eq 1 ); # Loop continues until one param is entered
}