2014-05-08 23 views
2

我想刪除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' 到$路徑 ''。我正確地獲取文件。

+0

也許你沒有舊的文件? '使用Data :: Dumper; print Dumper map [$ _,-f,-M],readdir DIR;' –

+0

@mpapec有第一個代碼打印文件的舊文件。 – norbdum

+0

添加到上面的一個班輪的問題輸出。 –

回答

2

您可以使用touch(用於測試)更改linux文件的日期。我認爲你的問題是,readdir只返回文件名,而不是文件的完整路徑。

你可以測試代碼這種方式(時間較長,但更容易理解):

#! /usr/local/bin/perl 
use strict; 
use warnings; 

my $dir = "/some/hardcoded/dir/here"; 
die unless opendir DIR, $dir; 
foreach my $file (readdir DIR) { 
    next if $file eq '.' or $file eq '..'; 
    $file = $dir.'/'.$file; 
    print "found $file, mtime: ".(-M $file)."\n"; 
    if (-f $file && (14 < -M)){ 
    print "unlinking $file\n"; 
    } 
} 
closedir DIR; 
+0

我想知道爲什麼我沒有使用'foreach $ file(grep {-f &&(0 <-M)} readdir DIR)'獲取文件,儘管'foreach $ file(readdir DIR)'這是打印文件名稱正確 – norbdum

+2

@nrobdum:打印循環打印名稱,但grepping循環嘗試訪問文件。如果您還沒有切換目錄('chdir'),名稱是相對於遠程目錄的,但您需要在名稱前加上目錄名稱和斜線以便能夠訪問這些文件。 –

+0

@JonathanLeffler現在感謝了! – norbdum

相關問題