It was Wednesday, December 01, 2004 when Gunnar Hjalmarsson took the soap box, 
saying:
: Casey West wrote:
: >The original question was places squarely within reasonable query
: >boundaries.
: 
: What do you refer to as "the original question"? To me it's this:
: http://www.mail-archive.com/beginners%40perl.org/msg64453.html

Yes. That's the question. An appropriate answer would look like the
following.

  There are a few concepts you need to understand to solve this
  problem. The first is opening and looping through files. Here's an
  example of how to do that.

    open FILE, "< file.txt" or die $!;

    while ( <FILE> ) {
        print $_; # prints one line at a time
    }

    close FILE;

  In your problem you want to parse lines to look for external files
  to loop through. In this case, the fourth element of
  each line is the file name so using split() to break the line into a
  list of parts is a good step. Here's what you do inside a while
  loop.

    my @line = split $_, /\s+/; # split on white space
    my $filename = $line[3];

  Next you wanted to open each file ($filename) and look through every
  line for some string and replace it. I'll assume that you've
  initialized these values as the variables $string and $replace.
  Using the same technique for looping over the file, this is what
  that might look like. Bear in mind that I'm going to open another
  file for writing so for every line read we write that line to the
  file. This can save memory.

    open SRFILE, "< $filename" or die $!;
    open OUTFILE, "> $filename.tmp" or die $!;

    while ( <SRFILE> ) {
      s/$search/$replace/g;
      print OUTFILE $_;
    }

    close OUTFILE;
    close SRFILE;

  Your final step was to rename the temp file to the name of the
  original file. Perl has a function for that too, rename().

    rename "$filename.tmp", $filename;

  There are the steps to solve your problem. It's a common problem and
  I would suggest some reading material. First, I'd read through a
  free online book called Beginning Perl. It's available in PDF form
  here: http://learn.perl.org/library/beginning_perl/

  There are sources in the Perl Documentation on your computer that
  will help as well. Here are some commands that will give you access
  to that documentation.

    perldoc -f open
    perldoc perlsyn
    perldoc perlre
    perldoc perl # for a table of contents

  Enjoy!

  Casey West

-- 
"A new swimming pool is rapidly taking shape since the contractors
have thrown in the bulk of their workers."
 --In an East African newspaper


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to