我有一个目录会创建每天的文件,例如“ 2018-08-14-9-22-4”, 创建的文件名是yyyy-mm-dd-h-m-s, 如何通过``2018-08-14''之类的子字符串检查文件是否存在? 并获取文件全名和文件大小?
my $file = "$yy-$mm-$dd-$hh-$mm-$ss";
my $path = '/home/httpd/doc/$user/$year/[every day file]'
答案 0 :(得分:4)
最简单的方法是使用glob
中的模式匹配,然后在文件上使用stat
。
for my $name ( glob('2018-08-14-*') ) {
my $size = ( stat($name) )[7];
say "name is '$name', size is $size bytes";
}
或更妙的是...使用File::stat
use File::stat;
for my $name ( glob('2018-08-14-*') ) {
my $size = stat($name)->size;
say "name is '$name', size is $size bytes";
}
我在r/perl上回答了一个类似的问题,如果您对做自己想做的事情的不同方式感兴趣,则值得阅读
更新
如果您创建了文件名变量,并且想要检查它是否存在,只需使用file test operators
my $file = "$yy-$mm-$dd-$hh-$mm-$ss";
my $path = "/home/httpd/doc/$user/$year/";
if (-e $path) { say "$path exists" }
if (-d $path) { say "$path is a dir" }
if (-w $path) { say "$path is a writeable" }
if (-e "$path/$file" && -r "$path/$file" ) {
say "$path/$file exists and is readable"
}
答案 1 :(得分:2)
您的路径(如果包含变量)应加双引号。如果路径是单引号,则$file
和$year
不会被插值
use v5.10;
use strict;
use warnings;
use File::Basename;
my ($user,$year) = @ARGV;
my $check = '2018-08-14';
opendir my $dir_handle, "/home/httpd/doc/$user/$year/";
# use File::Basename to get the filename from each file in the dir
# use regex to check if each filename starts with the string to check for
while (readdir $dir_handle) {
my $name = basename($_);
if ($name =~ /^$check/) {
say "$name found. size: ". -s $dir.$name;
}
}