pme has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

Just for curiosity I tried to use utf characters as subroutine names. My first attempt was using the Greek summa (Σ) as subroutine name. And it works well. Then I tried the integral sign (∫) and it just fails miserably.

Illegal declaration of anonymous subroutine at ./utf-2.pl line 8 (#1) (F) When using the sub keyword to construct an anonymous subroutin +e, you must always specify a block of code. See perlsub.
Could someone tell me what is the character set of a valid perl code?

Unfortunately utf encoded characters displayed as they were entered below, in the <code> section. My perl version is v5.26.2.

#!/usr/local/bin/perl use strict; use warnings; use utf8; use open qw(:std :utf8); #sub &#8747; # Integral, vim: insert mode ctrl-k In #{ # return 88; #} sub &#931; # Summa, vim: insert mode ctrl-k S* { my $sum; $sum += $_ for (@_); return $sum; } die "Usage: $0 4 3 6...\n" unless @ARGV; print '&#931;: »', &#931;(@ARGV), "«\n"; #print '&#8747;: »', &#8747;(@ARGV), "«\n"; exit 0;

Replies are listed 'Best First'.
Re: UTF encoded subroutine names
by haukex (Archbishop) on Jan 30, 2021 at 10:48 UTC

    The difference between the two symbols you've posted here is that Σ is U+03A3 GREEK CAPITAL LETTER SIGMA, while ∫ is U+222B INTEGRAL. If you use ∑ instead, that's U+2211 N-ARY SUMMATION, the same error happens, and if you use ʃ, U+0283 LATIN SMALL LETTER ESH, the error doesn't happen. As per Identifier parsing, identifiers under use utf8; must start with a character matching (?[ ( \p{Word} & \p{XID_Start} ) + [_] ]), and as per perluniprops, items from the Unicode block "Mathematical Operators" don't match that rule. Unfortunately, these symbols aren't quite equivalent of course, but if you want to use them as names for Perl subroutines, you'll probably have to stick with the lookalikes. Update: I also find this very useful: Unicode Utilities: Character Properties.

    use warnings; use 5.028; use experimental 'regex_sets'; use open qw/:std :utf8/; use charnames ':full'; my $PERL_IDENT_RE = qr/ (?[ ( \p{Word} & \p{XID_Start} ) + [_] ]) (?[ ( \p{Word} & \p{XID_Continue} ) ]) * /x; for my $c ( 0x2211, 0x03A3, 0x222B, 0x0283 ) { printf "%s U+%04X %s %s\n", chr($c), $c, charnames::viacode($c), chr($c) =~ /\A$PERL_IDENT_RE\z/ ? "matches" : "doesn't match"; }

    Output:

    ∑ U+2211 N-ARY SUMMATION doesn't match
    Σ U+03A3 GREEK CAPITAL LETTER SIGMA matches
    ∫ U+222B INTEGRAL doesn't match
    ʃ U+0283 LATIN SMALL LETTER ESH matches
    

    Update 2: BTW, also: Ʃ U+01A9 LATIN CAPITAL LETTER ESH matches.

      Thanks a lot.