我对此感到很生气,我正在尝试更改代码中显示的目录路径,但它不会工作,我做错了什么?
我期待$fulltitle
成为\\mynas\data\music\FABRICLive\17 - Rhodes For D - Furney.mp3
my $find = 'C:\Users\Bell';
my $replace = '\\mynas\data\music';
my $fulltitle = 'C:\Users\Bell\FABRICLive\17 - Rhodes For D - Furney.mp3';
$fulltitle =~ s/$find/$replace/;
print ("$fulltitle\n");
答案 0 :(得分:5)
use warnings;
use strict;
my $find = quotemeta 'C:\Users\Bell';
my $replace = '\\mynas\data\music';
my $fulltitle = 'C:\Users\Bell\FABRICLive\17 - Rhodes For D - Furney.mp3';
$fulltitle =~ s/$find/$replace/;
print("$fulltitle\n");
__END__
\mynas\data\music\FABRICLive\17 - Rhodes For D - Furney.mp3
warnings会给你一个关于错误的线索。
答案 1 :(得分:1)
使用正则表达式操作路径很糟糕。
use Path::Class::Dir qw();
use Path::Class::File qw();
my $old = Path::Class::Dir->new_foreign('Win32', 'C:\Users\Bell');
my $new = Path::Class::Dir->new_foreign('Win32', '\\\\mynas\data\music');
my $file = Path::Class::File->new_foreign('Win32', 'C:\Users\Bell\FABRICLive\17 - Rhodes For D - Furney.mp3');
$file->relative($old)->absolute($new)->stringify
# '\\mynas\data\music\FABRICLive\17 - Rhodes For D - Furney.mp3'
你在使用UNC path的目录的注释中犯了一个错误。必须使用反斜杠转义字符串文字中的双反斜杠,这就是the syntax的工作原理。
答案 2 :(得分:0)
my $find = 'C:\Users\Bell';
my $replace = '\\mynas\data\music';
my $fulltitle = 'C:\Users\Bell\FABRICLive\17 - Rhodes For D - Furney.mp3';
$fulltitle =~ s/\Q$find\E/${replace}/;
print "$fulltitle\n";
您需要使用\Q
和\E
来禁用匹配中的反斜杠元字符。
Codepad Example
注意:替换会将\\
翻译为\