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

第五章  输入与输出
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:$!";
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值