Reputation: 11
I'm trying to change the directory path as shown in the code, but it just wont work. What am I doing wrong?
I'm expecting $fulltitle
to be \\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");
Upvotes: 1
Views: 3867
Reputation: 39158
Manipulating paths with regex sucks.
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'
You made a mistake in the notation of the directory with the UNC path. Double backslashes in string literals must be escaped with backslashes, that's just how the syntax works.
Upvotes: 1
Reputation: 42099
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";
You need to use \Q
and \E
to disable the backslash metacharacter in the match.
Codepad Example
Note: the replacement will translate the \\
to \
Upvotes: 1
Reputation: 62037
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 would have given you a clue as to what was wrong.
Upvotes: 5