加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Perl语言入门(第五版) 读书笔记(二)---输入与输出、文件读写

发布时间:2020-12-16 00:04:25 所属栏目:大数据 来源:网络整理
导读:第五章? 输入与输出 1. 标准输入STDIN chomp($line=STDIN); while(defined($line=STDIN)) {} foreach(STDIN){print $_;} 2. 钻石操作符? 默认采用@ARGV数组作为输入,如果为空则改为STDIN 3. 调用参数列表@ARGV 4. printf() 格式化输入,print/printf不指定

第五章? 输入与输出
1. 标准输入<STDIN>
chomp($line=<STDIN>);
while(defined($line=<STDIN>)) {}
foreach(<STDIN>){print $_;}
2. 钻石操作符<>? 默认采用@ARGV数组作为输入,如果为空则改为<STDIN>
3. 调用参数列表@ARGV
4. printf() 格式化输入,print/printf不指定流时默认为STDOUT
use 5.010;
say "Hello!";? #say和print一样,但是会自动增加换行符
5. 打开文件句柄
open FH,"$file";? #read,default方式
open FH,"<$file";? #read
open FH,">$file";? #write
open FH,">>$file";? #append
open FH,"+<$file";? #read-update
open FH,"+>","/root/file";? #write-update
open FH,"+>>",$file;? #append-update
open FH,"| cat >hello";? #open pipe
close FD;
5. 用die处理严重错误,die可以输出信息并终止程序
?? warn和die用法一样,但是不会终止程序
6. 使用文件句柄
1)文件读取的3中方法
按行读,存入标量
while (<FILE>) { print; }
按行读,存入数组
@array = <FILE>;
读入整个文件 ,存入标量
$string = do { local $/; <FILE>; };
2)读文件实例
open (EP,"/etc/passwd");
while (<EP>)
{
?chomp;
?print "I saw $_ in the password file!n";
}
3)读写文件实例
open(IN,$a) || die "cannot open $a for reading: $!";
open(OUT,">$b") || die "cannot create $b: $!";
while ($line = <IN>)
{?
?print OUT $line;
}
close(IN) ;
close(OUT) ;

7. 复用标准文件句柄 select STDERR; #select能改变默认的文件句柄 复用文件句柄时,perl会自动关闭原来的文件句柄。 if (! open STDERR,">> /var/error.log") #将错误信息写到自定义文件中 { ??? die "Can't open error log for append:$!"; }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读