Marco Giardina wrote:

> Hi list,
>
> sorry but i'am a newbie about Perl. Perl is fantastic, anything is possible
> when use Perl..
> So i have a question about this language. In brief I'll modify some
> information inside a file, for example image a file test.conf.
> I'll erase some character (#) before a line and then eventually, after some
> time, rewrite the same information always (#).
>
> I must:
> - Open file
> - find a particular line or character
> - apply a line modification
> - close the file
>
> So does anyone if exist a simple, very simple example that explain this
> approach.
>
> Many, many thanks list
>
> Marco

Hi Marco,

First let us note--your general description of the task does not match the steps 
listed in the algorithm that follows.  Nor is your algorithm sufficiently precise.  Do 
you want the line, or the character?  There are different solutions.  It is your job 
as a programmer to decide what you want.

I'm going to assume that you are looking for a particular string within a line, and 
use a regular expression-based substitution:

usage:
ReplaceString.pl TargetString ReplacementString SourceFile
    Replaces TargetString with ReplacementString in SourceFile

#!/usr/bin/perl -w

use strict;
use warnings;

my ($TargetString, $ReplacementString, $SourceFile) = @ARGV;

ReplaceString ($TargetString, $ReplacementString, $SourceFile);

sub ReplaceString {
   my ($TargetString, $ReplacementString, $SourceFile) = @_;
   open IN, "< $SourceFile" or
    die("Could not open source file.\n$!");
   open OUT, "> $SourceFile" . '.tmp' or
    die("Could not open output file.\n$!");
   while (<IN>) {
      $_ =~ s/$TargetString/$ReplacementString/g;
      print OUT;
   }
   close IN or die("Source file did not close properly.\n $!");
   close OUT or die("Output file did not close properly.\n $!");
   rename $SourceFile . '.tmp', $SourceFile;
}

Original Sample.txt:

Ethics warning
Plagiarism is a violation of academic ethics
This violation consists of presenting the work of another, intentionally, as ones own.
It can result in disciplinary actions, including expulsion.

Call to ReplaceString:
>ReplaceString.pl Plagiarism cheating Sample.txt

Modified Sample.txt:

Ethics warning
cheating is a violation of academic ethics
This violation consists of presenting the work of another, intentionally, as ones own.
It can result in disciplinary actions, including expulsion.

Joseph


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to