in reply to Re^6: How to safely use $_ in a library function?
in thread How to safely use $_ in a library function?

Does Const::Fast work for you?

use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name
  • Comment on Re^7: How to safely use $_ in a library function?

Replies are listed 'Best First'.
Re^8: How to safely use $_ in a library function?
by Athanasius (Archbishop) on Sep 19, 2013 at 07:43 UTC

    Yes, it seems to work as advertised:

    17:39 >perl -Mstrict -wE "my $s = 42; say $s; ++$s; say $s;" 42 43 17:39 >perl -Mstrict -MConst::Fast -wE "const my $s => 42; say $s; ++$ +s; say $s;" 42 Modification of a read-only value attempted at -e line 1. 17:39 >

    How does that help?

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Const::Fast is basically just a wrapper around Internals::SvREADONLY.

      $ perldoc -m Const::Fast | grep SvREADONLY if (my $reftype = reftype $_[0] and not blessed($_[0]) and not &In +ternals::SvREADONLY($_[0])) { &Internals::SvREADONLY($_[0], 1); Internals::SvREADONLY($_[0], 1); croak 'Attempt to reassign a readonly variable' if &Internals::SvR +EADONLY($_[0]);
      use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

        Yes, Internals::SvREADONLY(..., 1) works to correctly make a writeable variable read-only:

        And Internals::SvREADONLY(..., 0) then works to make the variable writeable again:

        But it doesn’t work on a variable which is aliased to a literal:

        So Internals::SvREADONLY() “works” under Windows; but (it would appear) its effect on an aliased variable is not portable?

        Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,