Solutions:

perl -e'for ( 1 ) { my $x = pack "I", $_; }'
perl -e'for my $x ( 1 ) { my $y = pack "I", $x; }'
perl -e'for my $x ( 1 ) { my $x = pack "I", $x; }'
perl -e'for my $x ( my $tmp = 1 ) { $x = pack "I", $x; }'

Explanation:

1 returns a read-only scalar. It's read-only because a given 1 literal always returns the same scalar.

Foreach aliases the variable, so $x is an alias of that read-only scalar.

To understand what that means, it might be clearer if we take the foreach out of the equation.

use feature qw( say ); use experimental qw( refaliasing declared_refs ); my $y = 1; # Make `$y` have the same value as `1`. say $y; # 1 $y = 2; # Make `$y` have the same value as `2`. say $y; # 2 my \$x = \1; # Make `$x` an alias of `1`. say $x; # 1 $x = 2; # Modification of a read-only value attempted say $x;

Just like in your code, the last assignment in this program dies because it attempts to modify $x and thus the scalar to which 1 evaluates. It would be bad if 1 started to evaluate to a scalar with a value other than one.


In reply to Re: Modification of a read-only value attempted?!? by ikegami
in thread Modification of a read-only value attempted?!? by kikuchiyo

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.