afeiguo
求教:如何打开一个文件,既可以读,又可以追加写
我发现如果一个文件如下打开:
open FILE, ">>", "file_name"
只可以追加写,不可以读?
如果要读,还需要再重新打开:
open FILE, "<", "file_name"
能不能同时读和追加写?谢谢!
afeiguo
回复 #2 flw 的帖子
谢谢flw,
我看的是小骆驼书,第4版。刚学perl
我有点糊涂了, 看看下面这两段代码有何不同?
(1)
open FD, ">>", "file_name";
while (<FD>) {
if (/hello/i) {
print "match hello/n";
}
}
(2)
@ARGV = wq/file_name/;
while(<>) {
if (/hello/i) {
print "match hello/n";
}
}
为什么这两段的代码行为不同? 前者不能读和匹配,后者可以读和匹配。
[[i] 本帖最后由 afeiguo 于 2008-6-19 15:06 编辑 [/i]]
afeiguo
回复 #4 不死草 的帖子
可能楼上的误解了我的意思,重新叙述一遍:
我当前目录有关文件,文件名为"test"
下面这两段代码行为不同:
(1)
open FD, ">>", "test";
while (<FD>) {
if (/hello/i) {
print "match hello/n";
}
}
(2)
@ARGV = wq/test/;
while(<>) {
if (/hello/i) {
print "match hello/n";
}
}
但是,稍微改动一下,下面这两段代码的行为就相同了:
(1)
open FD, "<", "test";
while (<FD>) {
if (/hello/i) {
print "match hello/n";
}
}
(2)
@ARGV = wq/test/;
while(<>) {
if (/hello/i) {
print "match hello/n";
}
}
所以, 我想弄清楚的是:
为什么用open FD, ">>", "test"; 打开的文件句柄没有读的功能呢?
还是我的用法不正确?
ulmer
回复 #1 afeiguo 的帖子
open FILEHANDLE, MODE, EXPR
The available modes are the following:
[quote]
mode operand create truncate
read <
write > ✓ ✓
append >> ✓
[/quote]
Each of the above modes can also be prefixed with the + character to allow for simultaneous reading and writing.
[quote]
mode operand create truncate
read/write +<
read/write +> ✓ ✓
read/append +>> ✓
[/quote]
With "+>>" is READING and APPENDING mode But you must RESET the pointer position with seek()!
For example:
open F, '+>>', 'file.txt';
seek F, 0, 0;
while (<F>) {print $_;}
print F 'something new', "/n";
close F