janDro
janDro

Reputation: 1466

Perl not reading file when passed '+>>'

I am trying to put the contents of a file into an array for grepping purposes but for some reason it is failing to do so when I pass the '+>>' argument. However when I open two separate file handles to the same file with different arguments it works.

This works:

open( FILEHANDLE, '<', $file ) or $file_not_found = 1;
open( APPENDFH, '>>', $file );
my @file_list = <FILEHANDLE>;
print("This is my file list @file_list \n");

Prints:

This is my file list 2015-11-06 11:17:57Example

This does not:

open( FILEHANDLE, '+>>', $file ) or $file_not_found = 1;
my @file_list = <FILEHANDLE>;
print("This is my file list @file_list \n");

Prints:

This is my file list

Upvotes: 1

Views: 62

Answers (2)

ikegami
ikegami

Reputation: 385655

>> and +>> open the file for append (O_APPEND), which places the file cursor at the end of the file. You could move the file pointer using seek($fh, 0, SEEK_SET), or you could open the file using +<.

Upvotes: 4

choroba
choroba

Reputation: 241828

+>> opens the file at the end. You need to rewind to the beginning to read from it:

seek FILEHANDLE, 0, 0;

But you can then open the file directly with +<.

Upvotes: 5

Related Questions