题
我想解压缩压缩文件,例如 files.zip
, ,到与我的工作目录不同的目录。比如说,我的工作目录是 /home/user/address
我想将文件解压到 /home/user/name
.
我正在尝试按如下方式执行此操作
#!/usr/bin/perl
use strict;
use warnings;
my $files= "/home/user/name/files.zip"; #location of zip file
my $wd = "/home/user/address" #working directory
my $newdir= "/home/user/name"; #directory where files need to be extracted
my $dir = `cd $newdir`;
my @result = `unzip $files`;
但是,当从我的工作目录运行上述命令时,所有文件都会在工作目录中解压缩。如何将未压缩的文件重定向到 $newdir
?
解决方案
unzip $files -d $newdir
其他提示
使用 Perl 命令
chdir $newdir;
而不是反引号
`cd $newdir`
这将启动一个新的 shell,更改该 shell 中的目录,然后退出。
虽然对于这个例子,解压缩的 -d 选项可能是执行您想要的操作的最简单方法(如 ennukiller 提到的),但对于其他类型的目录更改,我喜欢 File::chdir 模块,它允许您本地化与 perl“本地”运算符结合使用时目录更改:
#!/usr/bin/perl
use strict;
use warnings;
use File::chdir;
my $files= "/home/user/name/files.zip"; #location of zip file
my $wd = "/home/user/address" #working directory
my $newdir= "/home/user/name"; #directory where files need to be extracted
# doesn't work, since cd is inside a subshell: my $dir = `cd $newdir`;
{
local $CWD = $newdir;
# Within this block, the current working directory is $newdir
my @result = `unzip $files`;
}
# here the current working directory is back to what it was before
您还可以使用 Archive::Zip 模块。具体看extractToFileNamed:
“extractToFileNamed($文件名)
将我提取到具有给定名称的文件中。该文件将以默认模式创建。将根据需要创建目录。$fileName 参数应该是文件系统上的有效文件名。成功时返回 AZ_OK。”
不隶属于 StackOverflow