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

While the other posters have focused on your direct problem and on your poor code flow. I'm wondering about your question of checking the readonlyness of a variable. My best stab is this:

sub is_readonly { eval {my $save=$_[0]; $_[0]=42; $_[0]=$save;}; return $@ =~/read.?only/; }

Can anybody come up with a cleaner way?

TACCTGTTTGAGTGTAACAATCATTCGCTCGGTGTATCCATCTTTG ACACAATGAATCTTTGACTCGAACAATCGTTCGGTCGCTCCGACGC

Replies are listed 'Best First'.
Re: Re: How could I check if a variable is 'read-only'?
by robin (Chaplain) on Jan 31, 2002 at 18:49 UTC
    I've talked about the Scalar::Util module before, and once again it comes to the rescue!
    use Scalar::Util qw(readonly); ... if (readonly $x) { ... }
    Get used to Scalar::Util and List::Util now - they're standard modules in 5.8.
Re^2: How could I check if a variable is 'read-only'?
by lifeboat (Initiate) on Jan 02, 2019 at 02:08 UTC
    Cleaner code is:
    sub is_readonly { eval {my $save=$_[0]; $_[0]=$save;}; return $@ =~/read.?only/; }
    Scalar::Util did not work for me.
      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.