Search code examples
perlutf-8

Convert normal letter to wide character


How for perl to convert from halfwidth to fullwidth form? In perl's term, from normal character to wide character.

E.g., from !abc ABC! to !abc ABC!. Arithmetically, the following should be correct

binmode STDOUT, ":utf8";

$letter = 'A';
$lw = chr($letter + 0xfee0);
print "Hello $lw ($letter)!\n";

But the print out is not what I was hoping for, which should be Hello A (A)!


Solution

  • If you had used use warnings you would have been given a warning that your addition failed:

    Argument "A" isn't numeric in addition (+) at ...

    Which means that your letter 'A' is cast into a number before addition, which will be 0 in this case. You can verify that by removing $letter + and just run the number in chr().

    You might fix your issue by fixing the logic:

    my $lw = chr(ord($letter) + 0xfee0);
    

    First changing the letter into numeric (ord()), and then doing addition.

    Note that to avoid simple mistakes like this, you should always use these pragmas:

    use strict;
    use warnings;