Modification of a read-only value attempted at ... line .... in a foreach loop

Viewed 57

I do not understand why the first two examples execute without any errors raised, but the third example causes problems. What is the difference here?

I understand that $0 and $1 etc are read-only variables. But why in the second example can I treat $i as an lvalue, but in the third example this treatment raising a modification of a read-only value error. The first example is there just to show I know how to work around this error, but I would like to understand why the second and third examples work as they do.

I'm posting this question here because any of the other similar questions posted here either explicitly or implicitly used $_, $0, etc. But I'm not doing that in my code. I don't understand why my $i is not an lvalue.

#!/usr/bin/perl
use strict;
use warnings;

print "Example 1\n";
foreach my $i ( 1..5,100 )
  {
    my $j = sprintf "%04s", $i;
    print ">> $j\n";
  }

print "\nExample 2\n";
foreach my $i ( 11..15 )
  {
    $i = sprintf "%04s", $i;
    print ">> $i\n";
  }

print "\nExample 3\n";
foreach my $i ( 21..25,100 )
  {
    $i = sprintf "%04s", $i;
    print ">> $i\n";
  }
0 Answers
Related