File::MMagic(3pm)

File::MMagic3pm

Guess file type

Usage

  use File::MMagic;
  use FileHandle;
  $mm = new File::MMagic; # use internal magic file
  # $mm = File::MMagic->new('/etc/magic'); # use external magic file
  # $mm = File::MMagic->new('/usr/share/etc/magic'); # if you use Debian
  $res = $mm->checktype_filename("/somewhere/unknown/file");
  $fh = new FileHandle "< /somewhere/unknown/file2";
  $res = $mm->checktype_filehandle($fh);
  $fh->read($data, 0x8564);
  $res = $mm->checktype_contents($data);

Abstract

This perl library uses perl5 objects to guess file type from filename and/or filehandle.

Overview

checktype_filename(), checktype_filehandle() and checktype_contents returns string contains file type with MIME mediatype format.

Methods

File::MMagic->new()
File::MMagic->new( $filename )

Initializes the module. If no filename is given, the magic numbers stored in File::MMagic are used.

$mm->addSpecials

If a filetype cannot be determined by magic numbers, extra checks are done based on extra regular expressions which can be defined here. The first argument should be the filetype, the remaining arguments should be one or more regular expressions.

By default, checks are done for message/news, message/rfc822, text/html, text/x-roff.

$mm->removeSpecials

Removes special regular expressions. Specify one or more filetypes. If no filetypes are specified, all special regexps are removed.

Returns a hash containing the removed entries.

$mm->addFileExts

If a filetype cannot be determined by magic numbers, extra checks can be done based on the file extension (actually, a regexp). Two arguments should be geiven: the filename pattern and the corresponding filetype.

By default, checks are done for application/x-compress, application/x-bzip2, application/x-gzip, text/html, text/plain

$mm->removeFileExts

Remove filename pattern checks. Specify one or more patterns. If no pattern is specified, all are removed.

Returns a hash containing the removed entries.

$mm->addMagicEntry

Add a new magic entry in the object. The format is same as magic(5) file.

  Ex.
  # Add a entry
  $mm->addMagicEntry("0\tstring\tabc\ttext/abc");
  # Add a entry with a sub entry
  $mm->addMagicEntry("0\tstring\tdef\t");
  $mm->addMagicEntry(">10\tstring\tghi\ttext/ghi");
$mm->readMagicHandle
$mm->checktype_filename
$mm->checktype_magic
$mm->checktype_contents

Releases

13 releases since Debian 3.0 (Woody); the text changed 7 times.

  1. 3.0
  2. 3.1
  3. 4.0–6.0
  4. 7
  5. 8–10
  6. 11–12
  7. 13
  8. Arch

From perl-file-mmagic 1.30-7 in Arch Linux 2026-11-01. Parsed by carta from the page's man source.