CJ7
CJ7

Reputation: 23295

Perl module for 'file' command?

On a Linux system I can use the file command to detect the type of a file.

Is there a perl module that encapsulates this command?

Upvotes: 5

Views: 628

Answers (2)

daxim
daxim

Reputation: 39158

File::MMagic's built-in magic is so short, it's useless. Avoid.

Instead use File::LibMagic, it's the best.

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

Upvotes: 2

Schwern
Schwern

Reputation: 165218

If you know you'll be on a sane Unix, you can just make a system call to file.

If you need an independent implementation, there are several available on CPAN. Probably the closest to file is File::MMagic. This is its own implementation, so it will work on any system, but might not act exactly like 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

Upvotes: 5

Related Questions