Question:

Help editing a document with Perl please!

by  |  earlier

0 LIKES UnLike

Hi, I love the knowledge of the YA! comuntity! In Perl, I know that the following will add text to the end of a file:

open (FILE, ">>test.txt");

print FILE "hey";

close (FILE)

How can I specify where for it to add the text in my document? Say I want it in DIV "one" or somewhere in the middle? Thanks!

 Tags:

   Report

3 ANSWERS


  1. Sorry for replying even though I don't know the answer. Just would like to say that it would be better if you visited those perl forums. Only the super geeks use perl, so there aren't many around here, I guess :)


  2. ======================

    You need 3 steps:

    1. open file for read:

    open (FILE, "<test.txt");

    $/=undef;  

    my $data=<FILE>;

    close (FILE);

    2. change data:

    $data=~s/one/one hey/s;

    3. write back:

    open (FILE, ">test.txt");

    print FILE $data;

    close (FILE);

    ======================

    You can also use tool Replace Pioneer, which support batch file replacement. You can just replace the first occurrance of "one" to "one hey....".

    Detailed steps:

    1. ctrl-o open source file

    2. ctrl-h open replace dialog

    set "Unit number filter" to 1, which means only replace first occurrance.

    set "Search for pattern" to the text you need to replace like 'one'

    set "Replace with pattern" to the new text like 'one hey...'

    3.  For single file, just click 'Replace', done

    For multiple files,

    (1)click 'Batch...' to open batch runner.

    (2)click "pick files" to select multiple files.

    (3)click "Batch Replace" to finish operation.

    ===========================

    Replace Pioneer free trial download: http://www.mind-pioneer.com

  3. use strict;

    use warnings;

    use File::Slurp;

    my $s = read_file('name.txt');

    # $s is the file contents.  

    # Change it to your heart's content (pun intended 8-)

    write_file('name.txt', $s);

    __END__

Question Stats

Latest activity: earlier.
This question has 3 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.