1. 文件名前面没有">"表示读文件
open(FILE,"C:\test.txt");
while(<FILE>)
{
chomp;
print "$_\n";
}
close(FILE);
2. 文件名前面有一个">"表示写文件,并覆盖原有内容
open(FILE,">C:\test.txt");
print FILE "大家好\n";
close(FILE);
3. 文件名前面有两个">"表示在这个文件后面追加内容
open(FILE,">>C:\test.txt");
print FILE "大家好\n";
close(FILE);
4. 一次性将文件中的所有内容读入一个数组中(该方法适合小文件):
open(FILE,"filename")||die"can not open the file: $!";
@filelist=<FILE>;
foreach $eachline (@filelist) {
chomp $eachline;
}
close FILE;
@filelist=<FILE>;
当文件很大时,可能会出现"out of memory"错误,这是可以采用如下方法,一次读取一行。
5. 一次从文件中读取一行,一行行地读取和处理(读取大文件时比较方便):
open(FILE,"filename")||die"can not open the file: $!";
while (defined ($eachline =<FILE>)) {
chomp $eachline;
# do what u want here!
}
close FILE;
6. STDIN, STDOUT, STDERR and DATA - Perl file handles
STDIN - Standard Input, for user control input, typically the keyboard
STDOUT - Standard Output,for regular use output, typically the screen
STDERR - Standard Error, for error output; typically defaults to the screen too
例print STDERR "this is an apple.";
DATA - Input for data stored after __END__ at the end of the program
open(FILE,"C:\test.txt");
while(<FILE>)
{
chomp;
print "$_\n";
}
close(FILE);
2. 文件名前面有一个">"表示写文件,并覆盖原有内容
open(FILE,">C:\test.txt");
print FILE "大家好\n";
close(FILE);
3. 文件名前面有两个">"表示在这个文件后面追加内容
open(FILE,">>C:\test.txt");
print FILE "大家好\n";
close(FILE);
4. 一次性将文件中的所有内容读入一个数组中(该方法适合小文件):
open(FILE,"filename")||die"can not open the file: $!";
@filelist=<FILE>;
foreach $eachline (@filelist) {
chomp $eachline;
}
close FILE;
@filelist=<FILE>;
当文件很大时,可能会出现"out of memory"错误,这是可以采用如下方法,一次读取一行。
5. 一次从文件中读取一行,一行行地读取和处理(读取大文件时比较方便):
open(FILE,"filename")||die"can not open the file: $!";
while (defined ($eachline =<FILE>)) {
chomp $eachline;
# do what u want here!
}
close FILE;
6. STDIN, STDOUT, STDERR and DATA - Perl file handles
STDIN - Standard Input, for user control input, typically the keyboard
STDOUT - Standard Output,for regular use output, typically the screen
STDERR - Standard Error, for error output; typically defaults to the screen too
例print STDERR "this is an apple.";
DATA - Input for data stored after __END__ at the end of the program