Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Need a little help appending lines

by moritz (Cardinal)
on Sep 11, 2007 at 20:32 UTC ( #638423=note: print w/replies, xml ) Need Help??


in reply to Need a little help appending lines

It's generally a bad idea to edit a file in place.

What I'd suggest is that you create a new file with the desired content, and the move the new file to the place of the old file.

You could first read things that you want to append into @list, and then do the "real" operation:

use File::Copy; # for move() open my $of, '<', $old_file or die "Can't read $old_file: $!"; open my $nf, '>', $new_file or die "Can't write $new_file: $!"; my $line_number = 0; while (my $line = <$of>){ chomp $line; print $nf $line, $list[$line_number]; } close $nf; close $of; move $new_file, $old_file;

Replies are listed 'Best First'.
Re^2: Need a little help appending lines
by shmem (Chancellor) on Sep 11, 2007 at 22:47 UTC
    It's generally a bad idea to edit a file in place.

    Is it? Why?

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
      It's a bad idea to edit a file in-place without a backup, let's just put it that way. Creating a separate output file from your source means your source *is* the backup. So moritz's point, a little less succinctly put, is, "Don't edit a file with important data unless you can undo any changes."

      (Or use version control.)
        Precaution against data loss is an entirely different thing, though related. But that concern doesn't justify marking in-place edits as bad idea, more so generally.

        Perl wouldn't have the -i switch if doing in-place edits wasn't a good idea. Generally speaking.

        --shmem

        _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                      /\_¯/(q    /
        ----------------------------  \__(m.====·.(_("always off the crowd"))."·
        ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://638423]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2023-03-21 07:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which type of climate do you prefer to live in?






    Results (59 votes). Check out past polls.

    Notices?