gemstone
07-11-2007, 03:11 AM
can anyone tell me how to open and close a txt file in perl?:(
|
Click to See Complete Forum and Search --> : open and close a text file gemstone 07-11-2007, 03:11 AM can anyone tell me how to open and close a txt file in perl?:( minulescu 07-11-2007, 06:41 PM If you want to open a file and write stuff to it, for example, open(FILE, example.txt); print FILE $someVariable; close(FILE); if you want to open to read fomr the file you can do something like open(FILE, example.txt); my i; my @fileLines; //array to hold the lines in text file while(<FILE>) //while there is stuff in FILE my $fileLines[i++]=$_; //put each line at an index in the array. close(FILE); //but you still have the contents of it in @fileLines Cheater 07-29-2007, 10:17 AM If you want to open a file and write stuff to it, for example, open(FILE, example.txt); print FILE $someVariable; close(FILE); if you want to open to read fomr the file you can do something like open(FILE, example.txt); my i; my @fileLines; //array to hold the lines in text file while(<FILE>) //while there is stuff in FILE my $fileLines[i++]=$_; //put each line at an index in the array. close(FILE); //but you still have the contents of it in @fileLines Your first example only opens the file to read from it. It should look like this: open(FILE, ">example.txt") or die "Can't open example.txt: $!"; Whenever you open a file, you should add the "or die" piece. That way, it tells you if there is an error. If you don't want it to die, you can replace it with "or warn" Amst 07-30-2007, 05:41 AM For opening and closing the files in perl , http://www.perlfect.com/articles/perlfile.shtml bluestartech 07-31-2007, 11:30 AM to open a file and read it there are two approaches, read whole file open(IN,'file.txt'); @lines = <IN>; close(IN); This is a neat solution since the file is closed straight after reading contents. However for large files it is best line by line, consuming less memory: open(IN,'file.txt'); while (<IN>) { print $_; # do whatever! } close(IN); close(IN); webdeveloper.com
Copyright Internet.com Inc., All Rights Reserved. |