|Just another Perl shrine|
|( #3333=superdoc: print w/replies, xml )||Need Help??|
You tried, directly or indirectly, to change the value of a constant. This type of error frequently occurs at a distance and is difficult to trace. The magic of $_ is often involved, but is not responsible.
In this example $x is aliased to the constant '1', so when the loop body attempts to increment $x an error is triggered. See Lists With Constant Values for more details.
Modifying $_ inside foreach, map or grep
In all of these examples $_ is aliased to a constant, and when the loop body attempts to modify $_ an error is triggered. See Lists With Constant Values for more details.
Modifying elements of @_ directly
Modifying elements of @_ directly allows you to modify the variable that was passed to the function. For example, in the above example $n is now 2. But an error will occur when a constant is passed, as in the second call.
Modifying $a or $b inside sort
It is permissible (but ill-advised) to modify $a and $b within sort. However, modifying a constant that is aliased to $a or $b is still an error.
Autovivifying $a or $b inside sort
The variables $a and $b are aliased to each item in the list being sorted, and as such modifying them is possible - but will cause an error if the current element is unmodifiable. A common cause of this is sorting an array of references when where the list has a gap. In this situation $a will be undef, and autovivification by dereferencing will trigger an error.
Modifying an unlocalized $_
This example will cause an error because the for loop aliases $_ to the literal '1', and then calls prompt_user which attempts to read a line from STDIN and store it in $_ - which is still aliased to '1'.
The error will also occur in this simplified scenario:
Guidelines to avoid read-only errors:
Lists With Constant ValuesWithin the context of this document the important thing to understand is what expressions result in modifiable objects. The following expressions have constants in them:
And the following are safe:
For an explanation of lists versus arrays I recommend the following: