2015-04-02 105 views
2

我調用從Perl程序vim編輯器以這樣的方式:如何確定退出vim時文件是否被修改?

my $cmd = "vi myfile"; 
system($cmd); 

然後我想根據執行不同的行動,文件的修改與否:

if(myfile was modified) { 
    doAction1; 
} 
else { 
    doAction2; 
} 

如何檢查如果文件被修改或沒有?我搜索了vim退出代碼,但沒有找到任何有用的東西。

+0

Hi @stanwar:if a ny答案已通過點擊複選標記解決了您的問題,請考慮[接受它](http://meta.stackexchange.com/q/5234/179419)。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 – 2015-04-15 09:04:12

回答

0

製作一個腳本,引入了tmp文件:

MYTMP=/tmp/perltimestamp.$$ 
file=myfile 
touch ${MYTMP} 
vi ${file} 
if [ $(find . -name ${file} -newer ${MYTMP} | wc -l) -gt 0 ]; then 
    rm ${MYTMP} 
    doAction1 
} else { 
    rm ${MYTMP} 
    doAction2; 
} 

當然你也可以在外面的if-then-else的移動rm命令,當你doActions是快速,安全。

3

最簡單的辦法是檢查文件的mtime

my $old_mtime = (stat $file)[9]; 
system('vi', $file); 
if ((stat $file)[9] != $old_mtime) { 
    # file modified 
} 
0

File::Modified module封裝MD5和修改時間檢查(寧願MD5如果安裝File::MD5):

use File::Modified; 
my $detector = File::Modified->new(files=>[$filename]); 
# [run the editor] 
if($detector->changed) { # [...] 

下面是一個完整的例子:

#!/usr/bin/perl 

use File::Modified; 

my $filename = 'myfile'; 
my $detector = File::Modified->new(files=>[$filename]); 

my $cmd = "vi $filename"; 
system $cmd; 

if($detector->changed) { 
    print "modified\n"; 
} else { 
    print "the same\n"; 
} 
相關問題