Results 1 to 5 of 5

Thread: perl question from a perl newb

  1. #1

    perl question from a perl newb

    How can I open a file and write back to it?

    For instance, I want to open a file, search for all instances of a word, replace them, then close the file. I'm assuming this is very simple, but being new to perl, I cannot figure out how to do this.

  2. #2

    Re:perl question from a perl newb

    You will open a file like this ...

    Code:
    open FILE, ">>/pathto/file";
    To search and replace you probably want to use regex stuff since it's the most powerfull and the simplest ...

    Code:
    s/replace/me/;
    or

    Code:
    $scalar =~ s/replace/me/;
    There are a few diffrent ways you can write back to the file. You could read the whole file in and do changes and then write it out, or attempt to change out line by line. I would probably choose the first way since it is easier to code and much simpler to bug fix.

    To print to a file all yu have to do is print to a filehandle ...

    Code:
    print $stuff FILE;
    Check out http://www.perlmonks.org as well as you might find the answer there.

  3. #3

    Re:perl question from a perl newb

    Try here (http://www.cgi101.com/class/).
    This tutorial explains opening files and reading and writing to them very well.

    Dizzy

  4. #4
    Mentor cga's Avatar
    Join Date
    May 2001
    Posts
    1,433

    Re:perl question from a perl newb

    8) Perlmonks 8)

  5. #5

    Re:perl question from a perl newb

    perl -e 's/foo/bar/g' -pi foo.txt

    but that's only if thats all you want to do. if you want to have it a part of a program it's more difficult. you'll need to open for read first:
    Code:
    open IN, "<foo.txt";
    open OUT, ">bar.txt";
    #then read the data
    while(<A>) {
      s/foo/bar/g;
      print OUT $_;
    }
    close IN;
    close OUT;
    good luck

Similar Threads

  1. Very simple newb Desktop question
    By mntamimi in forum Linux - General Topics
    Replies: 4
    Last Post: 09-14-2009, 02:29 PM
  2. Easy perl question
    By mcdougrs in forum Linux - Software, Applications & Programming
    Replies: 4
    Last Post: 01-11-2005, 08:25 PM
  3. newbie perl question using Net::OSCAR module
    By countach44 in forum Linux - Software, Applications & Programming
    Replies: 12
    Last Post: 12-10-2003, 04:09 AM
  4. PERL DBI Question
    By HuggyBear in forum Linux - Software, Applications & Programming
    Replies: 3
    Last Post: 08-16-2002, 02:45 PM
  5. Perl question about user input.
    By Feztaa in forum Linux - Software, Applications & Programming
    Replies: 4
    Last Post: 03-28-2002, 03:44 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •