On Wed Jun 17 2009 @ 3:42, Ajay Kumar wrote: > Hi Irfan > You can do all four task like below > > 1: open FILE ,">filename.txt" or die$!; > 2: my @lines=<FILE> > 3: do changes through sed > Like sed -e 's/original pattern/new pattern/p' filename > 4:if you did changes it automatically get saved > 5: close(FILE);
I hear that Perl can do some of this stuff too. For safety's sake, let's think of it as two tasks. First, read in data from file1, change the data in whatever ways we want, then print out the new version to file2. Nothing happens to file1 until that's finished. Second, we rename file1 to file1.bak (to keep a backup) and we rename file2 to file1. It all happens so fast that it feels as if we edited in place, but we didn't. #!/usr/bin/perl use warnings; use strict; # Let's use lexical filehandles, not barewords # And while we're at it, let's use the three-argument form of open # See perldoc -f open open my $in, '<', 'filename.txt' or die "Can't open [filename.txt] for reading: $!"; open my $out, '>', 'newversion.txt' or die "Can't create [newversion.txt] for writing: $!"; # Run through the file line by line for processing while (my $line = <$in>) { # code to make changes here print $out $line; # No comma! See perldoc -f print } # Close tidily or crash and burn close $in or die "Can't close [filename.txt]: $!"; close $out or die "Can't close [newversion.txt]: $!"; # The old switcheroo rename 'filename.txt', 'filename.txt.bak' or die "Can't rename [filename.txt]: $!"; rename 'newversion.txt', 'filename.txt' or die "Can't rename [newversion.txt] to [filename.txt]: $!"; This is a pretty simple thing to do in Perl, and there are ways to use more magic to make it briefer. In particular, see perldoc perlrun for how to use -i, -n, -p, -l and -e (not all at once, necessarily) to make this a simple one-liner in many cases. That said, there's nothing wrong with knowing how to do it yourself for more complex cases where a one-liner wouldn't cut it. -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/