【问题标题】:Error:Wide character in print at X at line 35, <$fh> ?(read text files from command line)错误:在第 35 行的 X 处打印宽字符,<$fh>?(从命令行读取文本文件)
【发布时间】:2017-02-12 22:17:08
【问题描述】:

我是 perl 的新手。这是我的第二个任务,我应该创建程序来解析 n 个文件并使用 n-grams 模型打印 m 个句子。长话短说,我编写了这个脚本,它将接受 n 个参数,其中第一个和第二个参数是数字,但其余的是文件名,但是我收到此错误 Wide character in print at ngram.pl line 35, line 1.

重现它的步骤:

命令行输入:perl ngram.pl 5 10 tale-cities.txt bleak-house.txt paper.txt
输出:在 ngram.pl 第 35 行第 1 行打印宽字符。

#!/usr/bin/perl
use strict;
use warnings FATAL => 'all';
use Scalar::Util qw(looks_like_number);
use utf8;
use Encode;
#Charles Dickens


sub checkIfNumberic
{
 my ($inp)=@_;
    if  (looks_like_number($inp)){
       return "True";
    }
    else{
        return "False" ;
    }
}
sub main
{
    my $correctInput=", your input must be something like this 5 10 somefile.txt somefile2.txt ";
    my @inputs= @ARGV;
    if (checkIfNumberic($inputs[0]) eq "False"){
        die "first argument must be numberic $correctInput\n";
    }
    if (checkIfNumberic($inputs[1]) eq "False"){
        die "second argument must be numberic $correctInput\n";
    }
    for (my $i=2;  $i< scalar @inputs ;$i++)
    {
        if (open(my $fh, '<:encoding(UTF-8)', $inputs[$i])) {
            while (my $line = <$fh>) {
                chomp $line;
                print "$line \n";
            }
        }
    }
}

main();

【问题讨论】:

  • 提示:使用my ($min, $max, @files) = @ARGV;
  • 提示:不要返回 TrueFalse(它们都是 true),返回一些 true(通常是 1)和一些 false(通常是 0),然后执行 @ 987654327@,或只是if (looks_like_number($min)){ ... }

标签: perl


【解决方案1】:

您解码了输入(脚本,use utf8;;文件,:encoding(UTF-8)),但您没有对输出进行编码。添加

use open ':std', ':encoding(UTF-8)';

这相当于

BEGIN {
   binmode STDIN,  ':encoding(UTF-8)';
   binmode STDOUT, ':encoding(UTF-8)';
   binmode STDERR, ':encoding(UTF-8)';
}

它还为在其词法范围内打开的文件句柄设置默认编码,您可以根据需要删除现有的:encoding(UTF-8)

【讨论】:

  • 感谢您的回答,我还有一个问题。你知道有什么好的模块可以解析巨大的文本文件并将字符串标记为二维数组或虚拟表
  • 非常不清楚的问题。发布一个问题,但有更多的细节。 (具体来说,“kind 2d array”和“virtual table”是什么意思?)
猜你喜欢
  • 2010-09-12
  • 1970-01-01
  • 1970-01-01
  • 2020-01-16
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多