0

我正在尝试读取我刚刚创建的文件 (a.txt) 的内容。该文件包含一个由“ABCDE”组成的字符串,然后我使用 write() 函数对其进行 tar。我可以看到在我的目录中创建了“a.tar”,但是当我使用 read() 函数时,我收到一个错误:无法读取 a.tar:在 testtar.pl 第 14 行。

难道我做错了什么 ?是因为我在 Windows 上吗?

use strict;
use warnings;
use Archive::Tar;
# $Archive::Tar::DO_NOT_USE_PREFIX = 1;

my $tari = Archive::Tar->new();
$tari->add_files("a.txt");
$tari->write("a.tar");

my $file = "a.tar";

my $tar = Archive::Tar->new() or die "Can't create a tar object : $!";
if(my $error = $tar->read($file)) {
    die "Can't read $file : $!";
}

my @files = $tar->get_files();
for my $file_obj(@files) {
my $fh = $file_obj->get_content();
binmode($fh);
my $fileName = $file_obj->full_path();
my $date = $file_obj->mtime();
print $fh;
}

谢谢。

4

2 回答 2

3

read您误解了of的返回值Archive::Tar

$tar->read ( $filename|$handle, [$compressed, {opt => 'val'}] )

返回在标量上下文中读取的文件数,以及Archive::Tar::File列表上下文中的对象列表。

请更改以下内容

if(my $error = $tar->read($file)) {
    die "Can't read $file : $!";
}

unless ($tar->read($file)) {
    die "Can't read $file : $!";
}

然后再试一次。

于 2014-05-15T07:46:42.903 回答
1

这是错误的:

my $fh = $file_obj->get_content();
binmode($fh);

get_content()为您提供文件的内容,而不是文件句柄。binmode()需要一个文件句柄。此外,您可以使用!defined而不是除非(我认为它更容易阅读)。

改写如下:

#!/bin/env perl
use strict;
use warnings;
use Archive::Tar;

my $tari = Archive::Tar->new();
$tari->add_files("a.txt");
$tari->add_files("b.txt");
$tari->add_files("c.txt");
$tari->add_files("d.txt");
$tari->write("a.tar");

my $file = "a.tar";

my $tar = Archive::Tar->new() or die "Can't create a tar object : $!";
if(!defined($tar->read($file)))
{
    die "Can't read $file : $!";
}

my @files = $tar->get_files();
for my $file_obj(@files)
{
    my $fileContents = $file_obj->get_content();
    my $fileName = $file_obj->full_path();
    my $date = $file_obj->mtime();
    print "Filename: $fileName Datestamp: $date\n";
    print "File contents: $fileContents";
    print "-------------------\n";
}
于 2014-05-15T09:12:14.450 回答