Prem Rexx
Prem Rexx

Reputation: 105

Write file in UTF-8 mode using Perl

I need to write a file with UTF-8 mode in Perl. How do i create that?

Can anyone help in this case?

I'm trying like this, Find my below code,

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

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

It's creating a file with UTF-8 Format. But i need to make sure whether that is happening from this script. Because if i'm writing a file without using utf8 encode also, File content is automatically taking as UTF-8 format.

Upvotes: 6

Views: 4389

Answers (1)

ikegami
ikegami

Reputation: 385645

You want

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

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

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

or

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";

Notes:

  • The encoding you want is utf-8 (case-insensitive), not utf8 (a Perl-specific encoding).
  • Don't use global vars; use lexical (my) vars.
  • If you leave off the instruction to encode, you might get lucky and get the right output (along with a "wide character" warning). Don't count on this. You won't always be lucky.

    # 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
    

Upvotes: 12

Related Questions