Here is a code snippet that basically rollsup a line until the keyword end; is reached then it prints it out. I believe the approach i am taking is called a closure (please correct me if i am wrong).
#!/usr/bin/perl use strict; use warnings; my $dummy = ""; my $rollup = combine(""); my $oneline; while (<DATA>) { $rollup->($_); # once end is reached store it in a variable # reset variable-in-sub for next iteration if (/end;/) { # breaks if I remove $dummy and replace it with "" $oneline = $rollup->($dummy); $rollup = combine(""); print $oneline,$/; } } sub combine { my $concat = shift; return sub { chomp($_[0]); $concat .= $_[0]; return ($concat); } }
Expected Output:__DATA__ line1; line2; line3; end; line4; line5; end;
line1;line2;line3;end; line4;line5;end;
The above code works just fine but when I use $oneline = $rollup->(""); instead of $oneline = $rollup->($dummy);
I get the following error -
Modification of a read-only value attempted at closure line 26, <DATA> + line 4.
Could you please explain to me what is the read-only value here?
I know i could do this whole step in a while loop and concatenate until end; is reached but wanted the flexibility in a sub and this also helps me learn more about closures :)
Thanks very much!
SK
Update: I have changed the title and took out the word closure as the problem is nothing to do with that.
In reply to Modification of read-only value error by sk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |