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

I'm running into a problem when I try to modify my referent variable in a foreach loop. According to my O'Reilly perl book, you modify each element in an array by modifying the loop variable inside the loop. Here's what I'm doing and the error message I'm getting. Thanks for your help! foreach $i ($1, $2, $3, $4, $5) { $i = int rand( scalar(@numb) + 1 ); pop @numb; } Modification of a read-only value attempted at line 7.

Replies are listed 'Best First'.
Re: Read-only variable in foreach loop?
by perlmonkey (Hermit) on May 08, 2000 at 07:03 UTC
    Your variables $1, $2, etc are read-only variables. In the foreach loop the $i is really a direct reference to $1 .. $5. So by modifying $i you are really trying to modify $1 .. $5, and you cannot do that. Here is an example:
    $_ = "##"; m/(##)/; $1 = "Hello"; Modification of a read-only value attempted at - line 3.
    To Fix your problem copy the read-only values to writeable variables:
    @list = ($1, $2, $3, $4, $5); foreach $i (@list) { $i = int rand( @numb +1 ); pop @numb; }
Re: Read-only variable in foreach loop?
by allogenes (Beadle) on May 08, 2000 at 07:15 UTC
    I'm not exactly sure what you're trying to do here,
    but the $1, $2 etc. variables are used for holding
    the results of RegEx parens matches. The $i in the
    foreach loop is taking a reference to each one of them
    in turn. I tried the snippet substituting $a, $b for
    the $1, $2 etc. and didn't get the error.
    Hopefully one of our senior monks can gives us a more
    indepth explanation...

    "all was created from /dev/null and shall return to /dev/null"
RE: Read-only variable in foreach loop?
by lhoward (Vicar) on May 08, 2000 at 07:09 UTC
    perlmonkey's explanation was better than mine so I nuked mine so as not to confuse the point