Perl学习笔记(4)文件的输出输入

本文介绍了使用Perl语言进行文件读写操作的方法,包括如何使用open函数打开文件、三种不同的打开方式及其作用、一次性读取文件内容的方法以及如何避免内存溢出错误。此外,文章还提到了Perl中用于标准输入、输出、错误输出和数据输入的特殊文件句柄,并通过实例演示了如何使用这些句柄进行数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值