简体   繁体   English

Perl文件I / O grep

[英]Perl File I/O grep

There may be syntax errors as I'm doing this from memory, but: 从内存中执行此操作时可能会出现语法错误,但是:

use strict;
use warnings;

open(FILE, "+>file") or die "can't open";
print FILE "foo";
if (grep {/^foo$/m}, <FILE>) {
   print "bar";
}
close(FILE) or die "can't close";

Why doesn't this print bar and how should I do this? 为什么没有此打印栏,我应该怎么做? I'm writing to a file and I need to check in the future if I've written certain things to the file before continuing, ie. 我正在写文件,以后需要检查是否已在文件中写了某些东西,然后再继续。 if foo already exists then don't write foo. 如果foo已经存在,则不要写foo。

Reading data from a file (eg, <FILE> ) starts reading from the current file pointer, not from the start of the file. 从文件(例如<FILE> )中读取数据开始从当前文件指针开始读取,而不是从文件开头开始读取。 In this case, that ends up being the end of the file — nothing gets read. 在这种情况下,最终将成为文件的末尾–没有读取任何内容。

If you wanted to restart reading from the beginning, you could seek to the beginning first: 如果您想从头开始重新阅读,可以先从头开始:

seek FILE, 0, 0;

However, keep in mind that this will be very inefficient. 但是,请记住,这将是非常低效的。 If you expect this to be a common operation, you'll be much better off storing the things you've written to an array and searching through that. 如果您希望这是一种常见的操作,那么最好将存储的内容存储到数组中并进行搜索。

There are a few problems with the code that could be causing this. 代码中可能存在一些问题,可能会导致这种情况。

The output to the file may be buffered so reading from the file will not see the output until after the buffer has been flushed to the file. 可能会缓冲文件的输出,因此从文件中读取数据将不会看到输出,直到将缓冲区刷新到文件之后。

In addition when you write to the file the file handle's location is moved to the end of where you have written so the read will not see it. 另外,当您写入文件时,文件句柄的位置将移至您写入位置的末尾,因此读取将看不到它。 This isn't tested but you should be looking along the lines of something like this. 这未经测试,但您应该遵循类似的思路。

use Modern::Perl;
use Fcntl qw(SEEK_SET);

open(my $file_handle, "+>", "file") or die "can't open";
print $file_handle "foo";
$file_handle->flush;
seek $file_handle, 0, SEEK_SET);

if (grep {/^foo$/m}, <$file_handle>) {
    print "bar\n";
}

close($file_handle) or die "can't close";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM