On 12/15/11 Thu  Dec 15, 2011  7:36 AM, "Melvin" <whereismel...@gmail.com>
scribbled:

> Hi,
> 
> I am a Perl baby :-)
> 
> I was trying to write a script to replace baby to bigboy in a file:-
> However the below script doesn't work Could someone help me???

The problem with your script is that you are not writing out the modified
strings to the file. Thus, the changes are lost when the program terminates.
Check 'perldoc -f open' for how to open a file for writing.

A more efficient program will open the original file for reading, open a new
file for writing (with a different name), read each line in the input file,
apply the change, then write the modified line to the output file. You can
use the following statements

    while( my $line = <FILE_IN> ) { ...

to read a line from the input file

    $line =~ s/baby/bigboy/g

to modify the line and

    print $file_out $line;

to write the file.

Note that it is generally better to use lexical variables ($file_out) rather
than globals (FILE_IN) for file handles.

It is also better to use the three-argument version of open.

Once you have the new file written successfully, you can rename it to the
old file name, either manually or within your program (using the rename
function). If you do the latter, first rename the old file so that you have
a backup, just in case.

> 
> #!/usr/bin/perl -w
> use strict;
> 
> open (FILE_IN , $ARGV[0]) || die ("ERROR: Gimme Input pleease");
> 
> my @array_of_lines = <FILE_IN>;
> 
> foreach my $line (@array_of_lines)
> 
> {
> $line =~ s/baby/bigboy/g;
> 
> }
> 
> close FILE_IN;
> 



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to