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

Hi, i'm very new to PERL language, can you please tell me why I am not able to modify the value of $a in below code line 3? an error "Modification of a read-only value attempted at test10.pl line 3. is displayed"

#!/usr/bin/perl -w $a=\100; #initialise $a to 100 and map it to it's address $$a=60; # modify the value of $a print $$a; #should print 60

Replies are listed 'Best First'.
Re: pass by referene
by davido (Cardinal) on Jun 30, 2011 at 21:34 UTC

    '100' is a literal. When you take a reference to a literal, it's still a literal. Literals cannot be altered.

    Think of it this way: You can take a reference to a number of "things". You can take a reference to an @array, to a %hash, to a $scalar, to a &sub, and even to a literal. If you modify the value of the target of your hash reference, you change the referent hash's value(s). If you modify the value of the target of a scalar ref, you modify the referent scalar container's value. But these are called variables for a reason; they hold variable data. Literals aren't, by their very definition, variable.

    An example:

    my $string = 'This'; my $number = 100; my $scalar_ref = \$string; # Take a reference to $string. $$scalar_ref = 'That'; # Modify the value of the scalar that # $scalar_ref refers to. print "$$scalar_ref = $string\n"; # That = That because we # changed the value of the # thing that $scalar_ref # points to, which happens to # also be what $string holds. $scalar_ref = \$number; # Change what $scalar_ref points to # doesn't change the referent values. print "$$scalar_ref isn't $string, it's $number\n";

    You can modify where a reference points, and can modify the values held in the variable containers referred to by the reference all day long if you want. But if your reference doesn't point to a variable container, but instead points to a literal value, all you can do is modify where it points, not what the underlying value is.


    Dave

Re: pass by referene
by choroba (Cardinal) on Jun 30, 2011 at 21:04 UTC
    You assing a reference to 100 to $a. Then you want to change the referenced object to 60 - but 100 cannot be changed. If you want the script to print 60, you do not need any reference:
    $var = 100; $var = 60; print $var;