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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With