1

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");
toolic
  • 57,801
  • 17
  • 75
  • 117
HeavyHead
  • 11
  • 1
  • 2
  • Does this help http://stackoverflow.com/questions/392643/how-to-use-a-variable-in-the-replacement-side-of-the-perl-substitution-operator – mathematician1975 Jul 04 '12 at 22:49

3 Answers3

5

quotemeta

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.

toolic
  • 57,801
  • 17
  • 75
  • 117
1
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 \

vol7ron
  • 40,809
  • 21
  • 119
  • 172
  • No idea what \Q and \E do exactly ... but only solution that worked when "\" are part of the search and replace. Even if within single brackets. (Only taken an hour to find this solutiion!) – Cristofayre Dec 22 '22 at 18:54
1

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.

daxim
  • 39,270
  • 4
  • 65
  • 132