Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl script messes with file descriptor in matlab

Tags:

io

perl

matlab

I use a perl script for replacing some strings in a data file. The perl script is called from within a matlab program, which writes to the data file before the execution of the perl script and after it's execution.

My matlab program would then write to the data file, but for some reason it does not.

Here is a minimal example: Matlab code:

f = fopen('output.txt','a');
fprintf(f,'This is written\n');
perl('replace.perl','output.txt');
fprintf(f,'This is not\n');
[fname perm] = fopen(f)
type('output.txt');
fclose(f);

perl script:

#!/usr/bin/perl -i
while(<>){
  s/This/This here/;
  print; 
}
close;  

The variables fname and perm are correctly assigned. The output of type is only "This here is written".

I am quite new to perl and so I probably make some rookie mistake in the script that I can't find. Thanks for helping.

like image 292
ben_za Avatar asked Jan 22 '15 15:01

ben_za


1 Answers

The secret is in the -i. In-place editing in perl, and in many other programs, is accomplished by opening the original file for reading, opening a temp file for writing, then unlinking the original file and renaming the temp file to the original file's name.

Now after running your perl script, poor matlab is left holding a file handle to a now unlinked file. You continue writing, but there's no easy way to see what was written... Even if the file had not changed out from under matlab, you would have had to deal with the fact that matlab was about to write to a spot that would now no longer be the end of the file.

In the end, you need to be very careful of having two programs/users/computers writing to the same file at the same time. Close the matlab file handle before calling perl. Reopen it for appending later if that proves to be really necessary.

like image 85
tjd Avatar answered Sep 28 '22 15:09

tjd