How to check if a file is a text file?

There's nothing built in, however there is a module Data::TextOrBinary that does that.

use Data::TextOrBinary;
say is-text('/bin/bash'.IO);                            # False
say is-text('/usr/share/dict/words'.IO);                # True

That's a heuristic that has not been translated to Perl 6. You can simply read it in UTF8 (or ASCII) to do the same:

given slurp("read-utf8.p6", enc => 'utf8') -> $f {
    say "UTF8";
}

(substitute read-utf8.p6 by the name of the file you want to check)


we can make use of the File::Type with the following code.

use strict;
use warnings;

use File::Type;

my $file      = '/path/to/file.ext';
my $ft        = File::Type->new();
my $file_type = $ft->mime_type($file);

if ( $file_type eq 'application/octet-stream' ) {
    # possibly a text file
}
elsif ( $file_type eq 'application/zip' ) {
    # file is a zip archive
}

Source: https://metacpan.org/pod/File::Type

Tags:

File Type

Raku