Gowri Chandra Sekhar Barla, TLS, Chennai wrote:
Hi
Hello,
I am unable to modify the input file ,
If I am redirecting output to with different file name it working fine
In want to replace name in a file
Perl provides a way to do that. It is called the "in-place edit"
switch(-i)/variable($^I):
perldoc perlrun
Script: problem
use warnings;
use strict;
print " Enter the file Name \n";
$filename = <STDIN>;
When you get input from STDIN it includes a trailing newline that you
have to remove to get the proper value:
chomp( my $filename = <STDIN> );
open(INPUT,"<$filename");
You should *always* verify that the file was opened correctly:
open INPUT, '<', $filename or die "Cannot open '$filename' $!";
open(OUTPUT,">filename");
When you open a file for output it truncates the file to 0 bytes
therefore this won't work.
while(<INPUT>)
{
if($_ =~ s/FRCC/FRE/)
{
print OUTPUT "$_";
}
else
{
print OUTPUT "$_";
}
You are missing the closing brace on the else block. But you don't need
the if-else part because they are both printing to the same filehandle.
The usual way to do what you want in Perl is this:
perl -i -pe's/FRCC/FRE/' filename
But if you are using Windows that won't work correctly without an
argument for the -i switch so:
perl -i.bak -pe's/FRCC/FRE/' filename
will work everywhere and also produce 'filename.bak' in case you want to
restore the original file.
To write that in a Perl program would be like this:
#!/usr/bin/perl
use warnings;
use strict;
# ensure that the file name is available on the command line
@ARGV == 1 or do {
print " Enter the file Name \n";
chomp( @ARGV = scalar <STDIN> );
};
# set the in-place edit variable
# use a non zero length string to save a back-up file
$^I = '';
# process the file
while ( <> ) {
s/FRCC/FRE/;
print;
}
__END__
Note that because your modification will produce a smaller file than the
original it would be possible to actually modify the file like you
described above.
John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order. -- Larry Wall
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/