Perl语言入门(第五版) 读书笔记(二)---输入与输出、文件读写
2013-12-13 15:54
555 查看
第五章 输入与输出
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:$!";
}
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:$!";
}
相关文章推荐
- 【翻译】使用新的Sencha Cmd 4命令app watch
- 【翻译】使用新的Sencha Cmd 4命令app watch
- 通过注册表控制软件可否运行
- B2B策划书:B2B行业网站未来5年发展趋势预测
- How to scan images, lookup tables and time measurement with OpenCV
- 多线程
- Genesis-3D学习手册——6.游戏对象
- HDU 1004
- Cocos2d-x使用android拍照功能加载照片内存过大,通过另存照片尺寸大小解决
- Hard 随机选择subset @CareerCup
- enter键触发事件
- linux相关书籍
- yum
- poj2503
- __declspec(dllimport)的作用究竟是什么?
- 数据备份基础之备份类型
- 复习——类(包含)
- Oracle数据库系统工程师培训视频教程下载
- InputStream,String,File相互转化
- log4j.properties详解