I have a directory will create every day file like '2018-08-14-9-22-4', the file name created is by yyyy-mm-dd-h-m-s, how to check file is exists by substring like '2018-08-14' ? and get the file full name and file size ?
my $file = "$yy-$mm-$dd-$hh-$mm-$ss";
my $path = '/home/httpd/doc/$user/$year/[every day file]'
Simplest way would be to use the pattern matching in glob
, and then use stat
on the file.
for my $name ( glob('2018-08-14-*') ) {
my $size = ( stat($name) )[7];
say "name is '$name', size is $size bytes";
}
or better yet... use 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";
}
I answered a similar question on r/perl that's worth reading if you interested in the different ways to do what you want
UPDATE
If you have created a filename variable, and you want to check if it exists, just use the 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"
}
Your path should be double-quoted, if it contains variables. If the path is single-quoted, $file
and $year
won't get interpolated
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;
}
}
来源:https://stackoverflow.com/questions/51832909/how-to-check-file-exists-and-get-file-size-by-substring