用于'file'命令的Perl模块?



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

是否有封装此命令的perl模块?

如果你知道你将在一个理智的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

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

最新更新