Hello everyone,

Hope you are all well. I'm relatively new to perl and I've been reading a not very useful book for a few weeks now. I have just finished learning "writing and reading files".

At the end of this chapter there are exercises and one of them is to insert a line in the middle of a file but the script I wrote does nothing.

The file I have looks like this:

Jonathan Peter Jason Nick Stela Samantha

And I want to insert the name Simon below Jason and above Nick without overwriting any of the existing names.

Jonathan Peter Jason Simon Nick Stela Samantha

The script I wrote is below but it doesn't print anything in the file and it doesn't give me any warnings or errors.

my $file = '/home/yanni/scripts/testfiles/list_names'; open my $NAMES, '+>>', $file || die "What the hell? Can't open file $! +\n"; while (<$NAMES>) { if ($.== 3) {print "\nSimon\n";} } close ($NAMES);

First, I open the file for reading and appending (+>>), then with the while command I read the file line by line (at least this is what it says in the book). Inside the while loop I "state" that when you read line 3 print the name Simon.

What am I doing wrong?

Any suggestions please?
Thanks a lot


In reply to Inserting a line in the middle of a text by goude

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.