Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write file in UTF-8 mode using Perl

Tags:

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.

like image 570
Prem Rexx Avatar asked Dec 23 '22 14:12

Prem Rexx


1 Answers

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
    
like image 114
ikegami Avatar answered Jan 02 '23 20:01

ikegami