Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 459
CJ7 Avatar asked May 12 '17 00:05

CJ7


2 Answers

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
like image 51
Schwern Avatar answered Sep 28 '22 16:09

Schwern


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'
};
like image 31
daxim Avatar answered Sep 28 '22 16:09

daxim