in reply to Re: How could I check if a variable is 'read-only'?
in thread How could I check if a variable is 'read-only'?

Cleaner code is:
sub is_readonly { eval {my $save=$_[0]; $_[0]=$save;}; return $@ =~/read.?only/; }
Scalar::Util did not work for me.

Replies are listed 'Best First'.
Re^3: How could I check if a variable is 'read-only'?
by syphilis (Archbishop) on Jan 02, 2019 at 05:02 UTC
    Scalar::Util did not work for me

    I would expect Scalar::Util to perform the task flawlessly.
    Could you provide an example script that demonstrates its failing ?

    Cheers,
    Rob

      There does look like one possibility. Perlguts mentions that with Perl 5.16 and earlier: Copy-on-write (see the next section) shared a flag bit with read-only scalars. So the only way to test whether sv_setsv , etc., will raise a "Modification of a read-only value" error in those versions is: SvREADONLY(sv) && !SvIsCOW(sv)

      Scalar::Util doesn't do anything special for 5.16 or earlier, so it could have false positives in that case. Of course, 5.18 (where it's fixed) was released in 2013 :)

      What do you make of this?

      #!/usr/bin/env perl use strict; use warnings; use JSON; use Scalar::Util qw/ readonly /; my $data = decode_json('{ "val":false }'); print "readonly: ", readonly($data->{val}) ? 'yes' : 'no', "\n"; bless $data->{val};

      That produces this for me (on Perl 5.18.2):

      $./try readonly: no Modification of a read-only value attempted at ./try line 10.
        cant reproduce that here, try upgrading perl and or json module