我正在創建一個腳本,我需要在其中獲取檔案的最后修改日期我檢查了這個執行緒如何在 Perl 中獲取檔案的最后修改時間?
所以我使用下面的腳本來獲取最后的修改,起初它可以作業,但是當我嘗試再次運行它時,時間戳回傳 1970 年 1 月 1 日 00:00。
為什么會發生這種情況,我怎樣才能獲得正確的最后修改日期和時間?
my $dir = '/tmp';
opendir(DIR, $dir) or die $!;
@content=readdir(DIR);
foreach(@content)
{
next unless ($_ =~ m/\bfile.txt|file2.csv\b/);
my $epoch_timestamp = (stat($_))[9];
my $timestamp = localtime($epoch_timestamp);
$f_detail = $_ .' '.$timestamp;
print "$f_detail\n";
}
closedir(DIR);
exit 0;
當我嘗試運行 perl 時,我會得到這個結果
file.txt 1970 年 1 月 1 日星期四 00:00:00
file2.csv 1970 年 1 月 1 日星期四 00:00:00
好的,上次更新,它現在正在運行,我嘗試運行你給我的所有腳本,獨立腳本。我找到了導致默認時間的原因,請參閱下面的腳本,我在我的程式中洗掉了它并且它可以作業,一開始沒有注意到這一點,抱歉。但是,仍然感覺很奇怪,因為當我第一次運行它時我確定它正在作業,但現在它正在作業,所以是的,謝謝你們!
if (($month = ((localtime)[4] 1)) < 10)
{
$month = '0' . $month;
}
if (($day = ((localtime)[3])) < 10)
{
$day = '0' . $day;
}
if (($year = ((localtime)[5] 1900)) >= 2000)
{
if (($year = $year - 2000) < 10)
{
$year = '0' . $year;
}
}
else
{
$year = $year - 1900;
}
$date = $month . $day . $year;
uj5u.com熱心網友回復:
readdir回傳沒有完整路徑的檔案名。您需要手動添加路徑:
for (@content) {
next unless /^(?:file\.txt|file2\.csv)\z/;
my $epoch_timestamp = (stat("$dir/$_"))[9];
# ~~~~~~~~~
另請注意我如何更改正則運算式以匹配檔案名。
uj5u.com熱心網友回復:
如果您有一個目錄名稱,并且您想查看該目錄中是否存在一些您已經知道名稱的檔案,那么實際上不需要opendir/ readdir- 如果您提前不知道檔案名,這將更有幫助。當你這樣做時,你可以只使用這兩個部分構建一個路徑并使用檔案測驗運算子stat//等。在上面。
#!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
my $dir = '/tmp';
my @files = qw/file.txt file2.csv/;
for my $file (@files) {
# Better to use File::Spec->catfile($dir, $file), but your question
# title said no modules...
my $name = "$dir/$file";
if (-e $name) { # Does the file exist?
# _ to re-use the results of the above file test operator's stat call
my $epoch_timestamp = (stat _)[9];
my $timestamp = localtime $epoch_timestamp;
say "$file $timestamp";
}
}
示例執行:
$ perl demo.pl
file.txt Tue Feb 8 07:26:07 2022
file2.csv Tue Feb 8 07:26:10 2022
uj5u.com熱心網友回復:
以下演示代碼利用glob獲取目錄中指定檔案的修改時間。
use strict;
use warnings;
use feature 'say';
my $dir = '/tmp';
my @files = qw(file.txt file2.csv);
my $mask = join ' ', map { "$dir/$_" } @files;
say "$_\t" . localtime((stat($_))[9]) for glob($mask);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425545.html
上一篇:在命令列上執行perl搜索和替換時,如何將匹配的標記小寫?
下一篇:Perl使用bash反引號
