Thursday, March 31, 2011

use encoding 'utf8" example

#!/usr/bin/perl 

use warnings;
use strict;

# Sort strings properly and match all letters
use locale;

# Read the source file as UTF-8 and set STDOUT and STDIN to UTF-8
use encoding 'utf8';


# We can write letters in the source code in UTF-8 thanks to "use encoding"
my @pole=qw(šiška marek ucho čaj žička);

# Sort knows our alphabet thanks to "use locale"
@pole=sort(@pole);           # sort array

foreach my $a (@pole) {
    # The pattern matching works fine thanks to "use locale"
    $a =~ s/\W//g;           # remove all non word characters
    print "$a \n";           # print the array field
}

# Write in UTF-8 into the file
open my $handle, ">:utf8", "file.txt" or die "Can't write to file.txt: $!";
# We can convert to upper case thanks to "use locale"
print $handle "\Uěščřžabcd\E\n";     # write upper cased string
close $handle;

No comments: