Perl将文件提取到特定位置

时间:2015-11-18 21:13:30

标签: perl

下面的脚本将ghc的源提取到一个名为'./incoming/ghc.tar.bz2'的文件夹中。似乎没有办法指定目标文件而不是目标目录(并且下载到标量只是为了稍后转储它似乎效率低下)。将文件下载到给定路径而不是给定路径指定的目录的首选方法是什么。我想避免依赖非核心模块或下载到tmp目录,只是为了尽可能将文件移动到其他地方。

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');

3 个答案:

答案 0 :(得分: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";

答案 1 :(得分:1)

您是否考虑过移动文件?:

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

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

或者,正如史蒂夫指出的那样,更好的选择是内置动作:

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

rename $where, "./incoming/ghc.tar.bz2";

答案 2 :(得分: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 $!;