in reply to Re^3: Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE ^]/ (updated)
in thread Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE ^]/

darn, constants are not interpolated in strings or regexes.

As I understand it, even with use constant, a constant in Perl is an in line sub. IE:

use constant PI => 4 * atan2(1, 1);

is the short hand for

sub PI { 4 * atan2(1, 1); }

Which, after compile time constant expression evaluation, simplifies to:

sub PI { 3.1415926536; # to the precision available on the machine running +the program }

which the compiler can then in line where it would otherwise put a sub call.

Replies are listed 'Best First'.
Re^5: Unmatched [ in regex; marked by <-- HERE in m/[ <-- HERE ^]/
by LanX (Saint) on Apr 29, 2014 at 17:01 UTC
    > where it would otherwise put a sub call.

    which isn't trivial within strings/regexes.

    the "@{[...]}" trick works but is IMHO a bit oversized for this task.

    DB<109> use constant STR => 1..3 DB<110> qr/[@{[ STR ]}]/ => qr/[1 2 3]/

    thats not interpolation anymore but inline eval.

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Here's another way, but I can't say it's any less klutzy. There seems to be no way to avoid the use of some kind of operator for disambiguation.

      use warnings; use strict; use constant STR => 'a string'; use constant STREF => \'ref to a string'; print qq{one way '${ \STR }' and another '${ +STREF }' \n}; print qq{and with another disambiguation '${ STREF() }' \n};

      Output:

      c:\@Work\Perl\monks>perl constant_interpolation_1.pl one way 'a string' and another 'ref to a string' and with another disambiguation 'ref to a string'