现有文件hello.txt,内容为:"你好'\n' 我是中国人"

1,打开文本hello.txt

#!/usr/bin/perl

open f,"hello.txt";

f 为文件句柄,指向打开的文件


2,逐行读取文本hello.txt

#!/usr/bin/perl

open f,"< hello.txt";

while($line=<f>){

print $line;

}

close f;

结果:你好

我是中国人

或者:print <f>;

结果:你好

我是中国人

<> 为取行操作符


3,向a.txt中写入内容

#!/usr/bin/perl

open f,">a.txt";

print f "hello,world\nsee you\n";

close f;

如果a.txt原本有内容,则原内容将会被擦除,a.txt的内容为

hello,world

see you

4,向a.txt中追加内容

#!/usr/bin/perl

open f,">>a.txt";

print f "thank you\n";

close f;

a.txt的内容为

hello,world

see you

thank you


print 相当于写命令,别丢了语句结尾的 “;"