Perl模块用于'file'命令?

5

在Linux系统上,我可以使用file命令来检测文件的类型。

是否有一个perl模块封装了这个命令?

2个回答

5

如果你知道你会在一个合理的Unix系统上运行,你可以直接调用系统函数file

如果你需要一个独立的实现,CPAN上有几个可供选择。可能最接近file的是File::MMagic。这是它自己的实现,因此它可以在任何系统上工作,但可能不完全像file那样操作。

$ head test.pl
#!/usr/bin/env perl

use strict;
use warnings;

$ file test.pl
test.pl: a /usr/bin/env perl script text executable, ASCII text

$ perl -wlE 'use File::MMagic; $mm = File::MMagic->new; say $mm->checktype_filename(shift)' test.pl
x-system/x-unix;  executable /usr/bin/env script text

@CJ7 如果docx文件使用zlib进行压缩,我不会感到惊讶。您可能需要将其与文件扩展名数据库结合使用。 - Schwern
我只是用它来处理一些没有扩展名的文件。 - CJ7

2
File::MMagic的内置魔法太简短了,没什么用。建议避免使用。
相反,使用File::LibMagic是最好的选择。
$ perl -mFile::LibMagic -MDDS -E \
    'say Dump(File::LibMagic->new
        ->info_from_filename("Startopia EULA English.docx"))'
$HASH1 = {
    description  => 'Microsoft Word 2007+',
    encoding     => 'binary',
    mime_type    => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    mime_with_encoding => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=binary'
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接