Perl script messes with file descriptor in matlab

I am using a perl script to replace some lines in a data file. The perl script is called from the matlab program, which is written to the data file before the perl script is executed and after it is executed.

Then my Matlab program will be written to the data file, but for some reason this is not the case.

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 conclusion of type is only "It is written here."

I am new to perl and so I probably made a rookie error in a script that I cannot find. Thanks for the help.

+5
source share
1 answer

The secret is in -i . In-place editing in perl and many other programs is done by opening the source file for reading, opening a temporary file for writing, then canceling the source file and renaming the temp file to the original file name.

Now, after running your perl script, the poor matlab remains to contain the file descriptor in a now unrelated file. You keep writing, but there is no easy way to see what was written ... Even if the file did not change from under Matlab, you would have to deal with the fact that Matlab was going to write in a place that will no longer end the file .

In the end, you have to be very careful while using two programs / users / computers in one file at the same time. Close the matlab file descriptor before calling perl. Re-run it to add later if it is really necessary.

+8
source

Source: https://habr.com/ru/post/1211706/


All Articles