Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does only one of these tell me "Modification of a read-only value attempted"?

Tags:

perl

This code runs and produces the output abc:

for(10..12){$_=sprintf"%x",$_;print}

But this code dies with a Modification of a read-only value attempted at ... error:

for(10,11,12){$_=sprintf"%x",$_;print}

Why are these constructions treated differently?

(This code also works:)

for(10..10,11..11,12..12){$_=sprintf"%x",$_;print}
like image 507
mob Avatar asked Sep 29 '12 01:09

mob


1 Answers

Probably because of the "counting loop" optimization that comes into play when you foreach over a range. for (1, 2, 3, 4) actually constructs the list (1, 2, 3, 4), containing those particular readonly values, but for (1..4) doesn't; it just iterates from the start of the range to the end, giving $_ each successive value in turn, and I guess nobody thought it would be worthwhile to match the behavior when you try to assign to $_ that closely.

like image 64
hobbs Avatar answered Oct 04 '22 14:10

hobbs