Dear monks,

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); } }
__DATA__ line1; line2; line3; end; line4; line5; end;
Expected Output:

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

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.