2015-11-18 55 views
1

以下腳本將源代碼提取到ghc到調用'./incoming/ghc.tar.bz2'的文件夾。似乎沒有辦法指定一個目標文件而不是一個目標目錄(並且將下載轉化爲標量以便稍後轉儲它似乎效率低下)。將文件下載到給定路徑而不是給定路徑指定的目錄的首選方式是什麼?我想避免依賴於非核心模塊或下載到tmp目錄,只是爲了將文件移動到其他地方,如果可能的話。Perl將文件提取到特定位置

use strict; 
use warnings FATAL => 'all'; 

my $ff = File::Fetch->new(
    uri => 'http://downloads.haskell.org/~ghc/7.10.2/ghc-7.10.2-src.tar.bz2'); 

my $where = $ff->fetch(to => './incoming/ghc.tar.bz2'); 
+1

你不不必下載到臨時目錄並移動文件。您可以將其存儲在實際的目標目錄中並對其進行重命名。或者使用[LWP](https://metacpan.org/pod/LWP),這或多或少是在Perl中處理網絡請求的標準方式。 –

回答

1

您可以簡單地在文件被提取後重命名文件。自動修改文件名是不必要的,但我反正把它扔了。

use warnings; 
use strict; 

use File::Basename; 
use File::Fetch; 

my $dir = './incoming'; 

my $ff = File::Fetch->new(
    uri => 'http://downloads.haskell.org/~ghc/7.10.2/ghc-7.10.2-src.tar.bz2' 
); 

my $where = $ff->fetch(to => $dir); 
my $fname = basename($where); 

rename $where, "$dir/$fname"; 
+0

以前的編輯讓我使用'File :: Copy'(http://perldoc.perl.org/File/Copy.html),但是'rename'與'File :: Copy :: move'做同樣的事情,並且它不需要另一個加載模塊(雖然'File :: Copy'是核心) – stevieb

+2

使用File :: Basename或File :: Spec(它們都是核心模塊)來分割路徑會更好。 –

+0

非常好的一點。我會在我回家的時候修復它,除非你傾向於;) – stevieb

1

你有沒有考慮剛移動後,該文件?:

... 
my $where = $ff->fetch(to => './incoming'); 

system("mv", $where, "./incoming/ghc.tar.bz2"); 

或者,如stevieb筆記,一個更好的選擇是內置的舉動:

... 
my $where = $ff->fetch(to => './incoming'); 

rename $where, "./incoming/ghc.tar.bz2"; 
1
use strict; 
use warnings; 

use File::Fetch; 
use File::Temp qw(tempdir); 

my $dir = '/Users/matt/Desktop'; 
my $ff = File::Fetch->new(uri => 'http://downloads.haskell.org/~ghc/7.10.2/ghc-7.10.2-src.tar.bz2'); 
my $where = $ff->fetch(to => tempdir(CLEANUP => 1)) or die $ff->error; 
my $file = $ff->file; 

while (-f "$dir/$file") { 
    # change name, append a number, whatever... 
    # $file = '...'; 
} 

rename($where, "$dir/$file") or die $!;