Wednesday, September 16, 2009

Perl File Example

The aim of this simple example is to show how to read and write a file in Perl. This will read from a file trim the white space at the start and end and append the result to another file.

First lets have a look at the example. It's really self explanatory.
 1. open (readfile, '<input.csv') or die "could not open file to read";
 2. open (writefile, '>>output.csv') or die "could not open file to write";
 3. while(<readfile>){
 4.     #read from 'readfile', trim and write to 'writefile'
 5.     $_ =~ s/(^ *| *$)//gi ;
 6.     print writefile $_;
 7. }
 8. close(readfile);
 9. close(sritefile);
Hide line numbers

No comments: