1

IO::File->open() 似乎不尊重在以下程序中使用 open() ,这对我来说很奇怪,并且似乎违反了文档。或者也许我做错了。重写我的代码以不使用 IO::File 应该不难。

我希望输出是

$VAR1 = \"Hello \x{213} (r-caret)";

Hello ȓ (r-caret)
Hello ȓ (r-caret)
Hello ȓ (r-caret)

但我收到此错误:“糟糕:./run.pl 第 33 行的打印中格式错误的 UTF-8 字符(字符串的意外结尾)。”

这对我来说似乎根本不对。

#!/usr/local/bin/perl

use utf8;
use v5.16;
use strict;
use warnings;
use warnings qw(FATAL utf8);
use diagnostics;
use open qw(:std :utf8);
use charnames qw(:full :short);

use File::Basename;
my $application = basename $0;

use Data::Dumper;
$Data::Dumper::Indent = 1;

use Try::Tiny;

my $str = "Hello ȓ (r-caret)";

say Dumper(\$str);

open(my $fh, '<', \$str);
print while ($_ = $fh->getc());
close($fh);
print "\n";

try {
  use IO::File;
  my $fh = IO::File->new();
  $fh->open(\$str, '<');
  print while ($_ = $fh->getc());
  $fh->close();
  print "\n";
}
catch {
  say "\nOops: $_";
};

try {
  use IO::File;
  my $fh = IO::File->new();
  $fh->open(\$str, '<:encoding(UTF-8)');
  print while ($_ = $fh->getc());
  $fh->close();
  print "\n";
}
catch {
  say "\nOops: $_";
};
4

2 回答 2

7

我相信这里发生的use open是一个词法编译指示,这意味着它只影响open()对同一词法范围内的调用。词法范围是当代码在同一个块中时。 IO::File->open是一个包装器open(),因此open()在其词法范围之外调用。

{
    use open;

    ...same lexical scope...

    {
        ...inner lexical scope...
        ...inherits from the outer...
    }

    ...still the same lexical scope...
    foo();
}

sub foo {
    ...outside "use open"'s lexical scope...
}

在上面的例子中,即使foo()调用 insideuse open的词法范围,里面的代码在foo()外面,因此不受它的影响。

如果 IO::File 继承了 open.pm 会很礼貌。这不是微不足道的,而是可能的。一个类似的问题困扰着autodie它已修复,修复可能在 IO::File 中起作用。

于 2013-01-30T02:28:08.830 回答
3

[这不是一个答案,而是一个不适合评论的错误通知。]

文件只能包含字节。$str包含不是字节的值。所以,

open(my $fh, '<', \$str)

没有意义。它应该是

open(my $fh, '<', \encode_utf8($str))

use utf8;
use v5.16;
use strict;
use warnings;
use warnings qw(FATAL utf8);
use open qw( :std :utf8 );
use Encode qw( encode_utf8 );
use Data::Dumper qw( Dumper );

sub dump_str {
   local $Data::Dumper::Useqq = 1;
   local $Data::Dumper::Terse = 1;
   local $Data::Dumper::Indent = 0;
   return Dumper($_[0]);
}

for my $encode (0..1) {
   for my $orig ("\x{213}", "\x{C9}", substr("\x{C9}\x{213}", 0, 1)) {
      my $file_ref = $encode ? \encode_utf8($orig) : \$orig;
      my $got = eval { open(my $fh, '<', $file_ref); <$fh> };
      printf("%-10s  %-6s  %-9s => %-10s => %s\n",
         $encode ? "bytes" : "codepoints",
         defined($got) && $orig eq $got ? "ok" : "not ok",
         dump_str($orig),
         dump_str($$file_ref),
         defined($got) ? dump_str($got) : 'DIED',
      );
   }
}

输出:

codepoints  ok      "\x{213}" => "\x{213}"  => "\x{213}"
codepoints  not ok  "\311"    => "\311"     => DIED
codepoints  not ok  "\x{c9}"  => "\x{c9}"   => DIED
bytes       ok      "\x{213}" => "\310\223" => "\x{213}"
bytes       ok      "\311"    => "\303\211" => "\x{c9}"
bytes       ok      "\x{c9}"  => "\303\211" => "\x{c9}"
于 2013-01-30T02:29:50.647 回答