2017-09-23 19 views
1

我需要在Perl中編寫一個使用UTF-8模式的文件。我如何創建?使用Perl以UTF-8模式編寫文件

任何人都可以幫助在這種情況下?

我想是這樣,我找到下面的代碼,

use utf8; 
use open ':encoding(utf8)'; 
binmode(FH, ":utf32"); 

open(FH, ">test11.txt"); 
print FH "something Çirçös"; 

它創建使用UTF-8格式的文件。但是我需要確定這個腳本是否發生了這種情況。因爲如果我在不使用utf8編碼的情況下編寫文件,文件內容也會自動以UTF-8格式顯示。

+0

是沒有意義的binmode不具有打開的句柄一個水珠。 – ikegami

回答

5

你想

use utf8;      # Source code is encoded using UTF-8. 

open(my $FH, ">:encoding(utf-8)", "test11.txt") 
    or die $!; 

print $FH "something Çirçös"; 

use utf8;      # Source code is encoded using UTF-8. 
use open ':encoding(utf-8)'; # Sets the default encoding for handles opened in scope. 

open(my $FH, ">", "test11.txt") 
    or die $!; 

print $FH "something Çirçös"; 

注:

  • 你想要的編碼是utf-8(不區分大小寫),不utf8
  • 請勿使用全局變量;使用詞彙(my)變量。
  • 如果您忘記編碼指令,您可能會很幸運並獲得正確的輸出(以及「寬字符」警告)。不要指望這一點。你永遠不會幸運。

    # Unlucky. 
    $ perl -we'use utf8; print "é"' | od -t x1 
    0000000 e9 
    0000001 
    
    # Lucky. 
    $ perl -we'use utf8; print "é♡"' | od -t x1 
    Wide character in print at -e line 1. 
    0000000 c3 a9 e2 99 a1 
    0000005 
    
    # Correct. 
    $ perl -we'use utf8; binmode STDOUT, ":encoding(utf-8)"; print "é♡"' | od -t x1 
    0000000 c3 a9 e2 99 a1 
    0000005 
    
+0

謝謝你的澄清。 –

相關問題