Here is how you can use perl to read from one file and write to another:
open(FILEREAD, "< file.read.name"); open(FILEWRITE, "> file.write.name"); while (<FILEREAD>){ print FILEWRITE; } close FILEWRITE; close FILEREAD; |
This will assign the file handle FILEREAD to the file file.read.name and start reading it in line by line in the while loop. The <> does the loop until FILEREAD is at the end of the file. The file handle FILEWRITE is assigned to the file file.write.name, and the file is opened for writing. You could print anything you want to file.write.name by using print, followed by the file handle, and then what you want to print. In this example, we simply print the current line from the file we are reading from, so all this script does, really, is copy a file. Of course, since you are doing this in perl, you can modify the lines to your hearts content. Notice that we don’t really have any error checking; however, we usually use this format to massage files line by line, and we know the files exist. Here is how this would work:
[root@main ruk]# echo stuff > file.read.name [root@main ruk]# cat file.read.name stuff [root@main ruk]# perl ruk.pl [root@main ruk]# ls file.read.name file.write.name ruk.pl [root@main ruk]# cat file.write.name stuff [root@main ruk]# |
We could modify the script:
#stuff open(FILEREAD, "< ruk.pl"); open(FILEWRITE, "> file.write.name"); $i=1; while (<FILEREAD>){ s/stuff/muchstuff/; print FILEWRITE $i.": ".$_; $i++; } close FILEWRITE; close FILEREAD; |
Notice we have changed the file we are reading to be the file we are running. We substitute stuff with muchstuff and add line numbers and colons to the beginning of the line:
[root@main ruk]# perl ruk.pl [root@main ruk]# cat file.write.name 1: #muchstuff 2: open(FILEREAD, "< ruk.pl"); 3: open(FILEWRITE, "> file.write.name"); 4: $i=1; 5: while (<FILEREAD>){ 6: s/muchstuff/muchstuff/; 7: print FILEWRITE $i.": ".$_; 8: $i++; 9: } 10: close FILEWRITE; 11: close FILEREAD; [root@main ruk]# |
Notice that the program eats itself. That is the s/stuff/muchstuff/ does just that on the listing output. For more details, see the manpage here.