Perl: Writing to a file

Writing to a file is very similar to reading it. And just, because reading and writing in perl is so easy and fast that Perl is ideal for scripting and data extraction purposes. Data can be written to another file using handles as follows: Suppose, you want to read a following file called “program.txt” that contains the following data (id and language) and write the languages part to another file “output.txt” using perl program:

1: perl 2: php 3: java 4: jsp

The program that would read this and print languages is:

#!/usr/bin/perl $fileName=”program.txt”; $outFile = “> output.txt”; # Note here the > sign. > sign writes to a file. >> sign appends to a file. open( fileHandle, $fileName); open(outFileHandle, $outFile); while(){ chop; # chop is used to remove \n (‘end of line’ from each line). my($id, $language) = split(‘:’, $_); print outFileHandle “Language is $language \n”; }

Note that adding “>” sign to the file name when opening it signifies that we want to write to the file. “>>” sign shows that we want to append to the file viagra tabletten. When writing to the file, we print to the hande as in statement we wrote to the handle outFileHandle:

print outFileHandle “Language is $language \n”;

The output.txt file now contains:

Language is perl Language is php Language is java Language is jsp

Comments on this entry are closed.

css.php