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

Yes, Internals::SvREADONLY is there all right:

1:35 >perl -E "say for sort keys %Internals::" SvREADONLY SvREFCNT V hv_clear_placeholders 1:35 >

But it doesn’t work for me. A Windows issue, maybe?

Thanks for the information on where to find the Internals package in the source code.

Update: I tried the Internals module, but that doesn’t work (for me, on Windows) either:

#! perl use strict; use warnings; use Internals qw(SetReadWrite); for (qw(literal1 literal2 literal3)) { print "$_\n"; foo('wilma'); } sub foo { SetReadWrite(\$_); $_ = 'fred'; goto &bar; } sub bar { my ($name) = @_; print "foo --> name = $name, \$_ = $_\n"; }

Output:

12:26 >perl 723_SoPW.pl literal1 Modification of a read-only value attempted at 723_SoPW.pl line 15. 12:28 >

Even IsWriteProtected fails:

#! perl use strict; use warnings; use Internals qw(IsWriteProtected); for (qw(literal1 literal2 literal3)) { print "$_\n"; foo('wilma'); } sub foo { if (IsWriteProtected(\$_)) { warn "Can't modify \$_"; } else { $_ = 'fred'; } goto &bar; } sub bar { my ($name) = @_; print "foo --> name = $name, \$_ = $_\n"; }

Output:

12:28 >perl 723_SoPW.pl literal1 Modification of a read-only value attempted at 723_SoPW.pl line 20. 12:36 >

:-(

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

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

    Does Const::Fast work for you?

    use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

      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