1

我对此感到很生气,我正在尝试更改代码中显示的目录路径,但它不起作用,我做错了什么?

我期待$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");
4

3 回答 3

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

警告会为您提供有关问题所在的线索。

于 2012-07-04T22:50:23.203 回答
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 路径的目录的符号中犯了一个错误。字符串文字中的双反斜杠必须用反斜杠转义,这就是语法的工作原理。

于 2012-07-05T04:26:33.560 回答
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禁用反斜杠元字符。
键盘示例


注意:替换将转换\\\

于 2012-07-04T23:18:20.293 回答