2015-03-13 48 views
0

我已经编写代码,但它不能正常工作。我希望将此“/”更改为此“\”。如何更新perl文本文件的某些部分

use strict; 
use warnings; 

open(DATA,"+<unix_url.txt") or die("could not open file!"); 

while(<DATA>){ 

s/\//\\/g; 
s/\\/c:/; 
print DATA $_; 

} 

close(DATA); 

我的原始文件

/etc/passwd 
/home/bob/bookmarks.xml 
/home/bob/vimrc 

预期输出是

C:\etc\passwd 
C:\home\bob\bookmarks.xml 
C:\home\bob\vimrc 

原始输出

/etc/passwd 
/home/bob/bookmarks.xml 
/home/bob/vimrc/etc/passwd 
\etc\passwd 
kmarks.xml 
kmarks.xml 
mrcmrc 

回答

1

试图读写在一个while循环中,一行一行地读取同一个文件直到该文件结束,看起来非常危险且不可预知。我一点也不确定你的文件指针会在你每次写入时结束。你会更安全地将你的输出发送到一个新的文件(然后如果你愿意,然后移动它来替换你的旧文件)。

open(DATA,"<unix_url.txt") or die("could not open file for reading!"); 
open(NEWDATA, ">win_url.txt") or die ("could not open file for writing!"); 

while(<DATA>){ 
    s/\//\\/g; 
    s/\\/c:\\/; 
    #  ^(note - from your expected output you also wanted to preserve this backslash) 
    print NEWDATA $_; 
} 

close(DATA); 
close(NEWDATA); 
rename("win_url.txt", "unix_url.txt"); 

参见此答案: Perl Read/Write File Handle - Unable to Overwrite

0

你并不真的需要写一个程序就实现这个。您可以使用Perl派:

perl -pi -e 's|/|\\|g; s|\\|c:\\|;' unix_url.txt 

但是,如果你在Windows上运行,你使用Cygwin,我会建议使用cygpath工具转换POSIX路径到Windows路径。

此外,您还需要引用您的路径,因为它允许在windows路径中有空格。或者,你可以摆脱空间字符:

perl -pi -e 's|/|\\/g; s|\\|c:\\|; s| |\\ |g;' unix_url.txt 

现在关于您最初的问题,如果你仍然想使用自己的脚本,你可以使用这个(如果你想备份):

use strict; 
use autodie; 
use File::Copy; 

my $file = "unix_url.txt"; 
open my $fh, "<", $file; 
open my $tmp, ">", "$file.bak"; 
while (<$fh>) { 
    s/\//\\/g; 
    s/\\/c:/; 
} continue { print $tmp $_ } 
close $tmp; 
close $fh; 
move "$file.bak", $file; 
+6

艇员选拔不同的字符防止倾斜牙签综合症:'S =/= \\ =克;' – choroba 2015-03-13 09:51:21

1

如果练习的要点是少谈使用正则表达式,并详细了解做事情,我会考虑使用从File::Spec系列模块:

use warnings; 
use strict; 
use File::Spec::Win32; 
use File::Spec::Unix; 
while (my $unixpath = <>) { 
    my @pieces = File::Spec::Unix->splitpath($unixpath); 
    my $winpath = File::Spec::Win32->catfile('c:', @pieces); 
    print "$winpath\n"; 
} 
相关问题