sergiotarxz
sergiotarxz

Reputation: 540

Interpolate variable inside \N

I want to make a script which should be able to transform the input to small capitals. I've tried the following code

use strict;
use warnings;
use utf8;
use feature qw(say);
binmode STDOUT, ":utf8";
my $text = join '',<STDIN>;
say $text=~s/[a-zA-Z]/\N{LATIN LETTER SMALL CAPITAL $&}/gr;

But I get

Unknown charname '"LATIN LETTER SMALL CAPITAL $&"' at small.pl line 7, within string Execution of small.pl aborted due to compilation errors.

I am open to other ways to do it.

Upvotes: 1

Views: 61

Answers (2)

H&#229;kon H&#230;gland
H&#229;kon H&#230;gland

Reputation: 40748

\N{} is a compile-time construct. One solution is therefore to generate code and evaluate it. s/// has built-in support for this in the form of /ee.

use open ':encoding(UTF-8)';
use feature qw(say);

my $text = 'A';
say $text =~ s/([a-zA-Z])/ qq{"\\N{LATIN LETTER SMALL CAPITAL $1}"} /eer;

How this works:

  1. The first e causes qq{"\\N{LATIN LETTER SMALL CAPITAL $1}"} to be evaluated, producing "\N{LATIN LETTER SMALL CAPITAL A}".
  2. The second e causes "\N{LATIN LETTER SMALL CAPITAL A}" to be evaluated, producing .
  3. The A is substituted with .

Upvotes: 1

daxim
daxim

Reputation: 39158

\N{} is a compile-time construct. Use charnames to look up a character by name at run-time.

perl -C -mcharnames -E'
    say chr charnames::vianame(
        "LATIN LETTER SMALL CAPITAL " . $_
    ) for qw(I N R)
'

Upvotes: 5

Related Questions