Gloom has asked for the wisdom of the Perl Monks concerning the following question:

Noble monks,

How can i know if a variable is readonly ? I've got the problem with chomp that raise some warns on readonly value. Is there any way to handle that other than eval ?

Thank's fellows.

Replies are listed 'Best First'.
Re: Readonly variable
by japhy (Canon) on Feb 26, 2001 at 22:33 UTC
    You could find out with the Devel::Peek module, but that's probably too much effort.
    sub is_readonly { eval { substr($_[0],0,0) = '', 1 } }

    japhy -- Perl and Regex Hacker
      do you mean sub is_readonly { eval { substr($_[0],0,0) = '' ; 1 } } ?

      This way is very smart. I will use it, thx :)

        You can use a comma or a semicolon, there is no difference. An even shorter (faster?) approach might be: sub is_readonly { eval { $_[0] = $_[0], 1 } }

        japhy -- Perl and Regex Hacker
Re (tilly) 1: Readonly variable
by tilly (Archbishop) on Feb 26, 2001 at 22:44 UTC
    Most of the time when I have seen complaints that a variable is readonly when it wasn't obvious why, I found that it was due to a bug in my program (improperly accessing a loop variable that was global from within a sub.

    After I got in the habit of aggressively making things private with my, and catching that with strict, I stopped ever running into that message.


      use strict; use diagnostics;
      are excellent companions to use strict
        You probably meant to turn on warnings as the second companion?

        While those are good companions, based on my experience when I see that message I take a WAG that the message is really a sign of a non-obvious problem. At least that is how that message has worked for me. Sometimes having Perl tell you why it is giving you the message is not as useful as having someone with some scars tell you what the likely error is that caused that message...

Re: Readonly variable
by unixwzrd (Beadle) on Feb 26, 2001 at 22:36 UTC
    Try this:
    #!/usr/bin/perl -w my $const = \"Something\n"; chomp( my $newvar = $$const ); print "$newvar "; print "Should be on the same line...\n";

    Mike -

    "The two most common elements in the universe are hydrogen... and stupidity."
    Harlan Ellison

Re: Readonly variable
by InfiniteSilence (Curate) on Feb 27, 2001 at 03:04 UTC
    Did anybody use:
    perl -e "*m = 100; $m=20;"
    Modification of a read-only value attempted at -e line 1

    Celebrate Intellectual Diversity