我想刪除x天前的文件,並在perlmonks Find files older than x days and delete them上得到這個頁面。以下是代碼做相同的(我的理解將刪除DIR是超過14天的文件):Perl:打開和讀取目錄並使用grep來過濾結果
#! /usr/local/bin/perl
my $path = '../some/hardcoded/dir/here';
die unless chdir $path;
die unless opendir DIR, ".";
foreach $file (grep {-f && (14 < -M)} readdir DIR) {
print $file;
#unlink $file;
}
closedir DIR;
,但我不希望更改目錄(CHDIR),因此改變了代碼如下但它不是打印文件名
die unless opendir DIR, $path;
foreach $file (grep {-f && (14 < -M)} readdir DIR) {
print $file;
#unlink $file;
}
closedir DIR;
即使這是正確打印文件。
die unless opendir DIR, $path;
foreach $file (readdir DIR) {
print $file;
#unlink $file;
}
closedir DIR;
我試圖尋找答案,但無法清楚地勾勒出問題。請解釋如何在不改變目錄(chdir)的情況下使用grep並獲取當前目錄文件。編輯
:輸出的print Dumper map [$_, -f, -M], readdir DIR;
$VAR1 = [
'PRTS_5_Thu_May_8_11-47-19_2014.pdf',
undef,
undef
];
$VAR2 = [
'.',
'',
'0.0891203703703704'
];
$VAR3 = [
'PRTS_49_Thu_May_8_12-31-11_2014.pdf',
undef,
undef
];
$VAR4 = [
'PRTS_34_Thu_May_8_12-27-03_2014.pdf',
undef,
undef
];
$VAR5 = [
'..',
'',
'9.02722222222222'
];
編輯2: 當我改變從 '../some/hardcoded/dir/here' 到$路徑 ''。我正確地獲取文件。
也許你沒有舊的文件? '使用Data :: Dumper; print Dumper map [$ _,-f,-M],readdir DIR;' –
@mpapec有第一個代碼打印文件的舊文件。 – norbdum
添加到上面的一個班輪的問題輸出。 –