Jan 3, 2007

Intermediate #1, File Handling

#!c:/www/perl/bin/perl

$file = "D:/My Perls/data.txt";
open(INFILE, $file);
@lines = <INFILE>;
close(INFILE);

foreach(@lines){
print $_;
}


INFILE is the file handler, no quotes is to be added. It can be replaced with any arbitual names.

<INFILE>reads in the entire file in one go, if a scalar variable is used instead of the array, then only the next line would be read in.

-----------------------------------------------------------------
open(INFO, $file); # Open for input
open(INFO, ">$file"); # Open for output
open(INFO, ">>$file"); # Open for appending
open(INFO, "<$file"); # Also open for input

*can add the - or die("error :".$!) for error handling
-----------------------------------------------------------------

if the file is already opened for output,
we can print to the file with the print statement with an additional parameter :

print INFO "END OF FILE\n";

-----------------------------------------------------------------

Standard Input and Output:
open(INFO, '-'); # Open standard input
open(INFO, '>-'); # Open standard output

No comments: