Does Perl6 have something like the Perl5 -T file test to tell if a file is a text file?
Asked
Active
Viewed 1,980 times
3 Answers
23
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

Jonathan Worthington
- 29,104
- 2
- 97
- 136
11
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)

jjmerelo
- 22,578
- 8
- 40
- 86
-
2actually, if the file isn't valid utf8, this will throw an exception. also, it won't understand utf16, for example – timotimo Apr 15 '19 at 09:02
-
1@timotimo right, but the original one just checked for ASCII or UTF8. A battery of encodings should have to be checked, but the general idea would be the same. – jjmerelo Apr 15 '19 at 09:19
-
1@jjmerelo Your comment disagrees with the answer to https://stackoverflow.com/questions/899206/how-does-perl-know-a-file-is-binary – plugwash Apr 15 '19 at 16:43
5
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
}

Sandy P. Chaudhry
- 118
- 6
-
-
2This could be edited to `use File::Type:from
` and `$ft.mime_type($file)` to be Perl6 code. – Brad Gilbert Apr 18 '19 at 19:30