【问题标题】:Archive::Tar : can't read tar created just before in PerlArchive::Tar : 无法读取之前在 Perl 中创建的 tar
【发布时间】:2014-05-15 20:26:51
【问题描述】:

我正在尝试读取我刚刚创建的文件 (a.txt) 的内容。该文件包含一个由“ABCDE”组成的字符串,然后我使用 write() 函数对其进行 tar。我可以看到在我的目录中创建了“a.tar”,但是当我使用 read() 函数时,我收到一个错误:Can't read a.tar : at testtar.pl line 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;
}

谢谢。

【问题讨论】:

    标签: perl tar archive-tar


    【解决方案1】:

    你误解了Archive::Tarread的返回值:

    $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 : $!";
    }
    

    然后再试一次。

    【讨论】:

    • 好的,现在它正在处理您的更正。你能解释一下为什么我的不正确吗?是否因为 read 正在“读取”一个文件并评估为 true,从而进入 die 语句?
    • @Hawknight read 返回 1 表示a.tar 中有一个文件,您使用该返回值作为条件,if 语句将其解释为 true,因此 @ 987654331@ 将运行。
    • 好的,我现在明白了。我将方法从 Archive::Zip 复制/粘贴到 Archive::Tar,但有些方法的工作方式不同。感谢您的回答!
    【解决方案2】:

    这是错误的:

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

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

    改写如下:

    #!/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";
    }
    

    【讨论】:

    • 感谢您的建议!如果我仍然保留 binmode,我会收到一条警告消息 :) 我必须承认 !defined 比除非更容易阅读,很好的洞察力
    猜你喜欢
    • 2020-07-01
    • 2015-12-15
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2013-09-13
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多