【发布时间】:2019-04-15 06:42:28
【问题描述】:
Perl6 是否有类似 Perl5 -T file test 的功能来判断文件是否为文本文件?
【问题讨论】:
Perl6 是否有类似 Perl5 -T file test 的功能来判断文件是否为文本文件?
【问题讨论】:
没有内置任何东西,但是有一个模块 Data::TextOrBinary 可以做到这一点。
use Data::TextOrBinary;
say is-text('/bin/bash'.IO); # False
say is-text('/usr/share/dict/words'.IO); # True
【讨论】:
这是has not been translated to Perl 6 的启发式方法。你可以简单地用 UTF8(或 ASCII)读取它来做同样的事情:
given slurp("read-utf8.p6", enc => 'utf8') -> $f {
say "UTF8";
}
(用你要检查的文件名替换read-utf8.p6)
【讨论】:
我们可以通过以下代码使用 File::Type。
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
}
【讨论】:
use File::Type:from<Perl5>和$ft.mime_type($file)成为Perl6代码。