Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: replace part of directory

by Util (Priest)
on Aug 22, 2009 at 20:12 UTC ( [id://790607]=note: print w/replies, xml ) Need Help??


in reply to replace part of directory

When you put a variable in the first section of a s/// substitution, the variable's contents are used as a pattern, not as a simple string. So, c:\top is understood as 5 characters, with the middle character being a TAB ("\t"). You can fix this by using quotemeta.

I would also add a start-of-string anchor to be safer.

You may need something like make_path from File::Path instead of mkdir when creating multiple levels of directory all at once.

Working, tested exmaple code:

#!/usr/bin/perl use strict; use warnings; my $dir = 'c:\top\dir\file'; my $oldroot = 'c:\top'; my $newroot = 'c:\newtop'; my $newdir = $dir; print "Oldroot will be used as the pattern; It is '$oldroot'\n"; print "newdir was: '$newdir'\n"; $newdir =~ s/$oldroot/$newroot/ or warn "Can't find pattern '$oldroot' in dir string '$newdir'"; print "newdir now: '$newdir'\n\n"; my $oldroot_regex = quotemeta $oldroot; #$oldroot_regex = '^' . $oldroot_regex; # I would do this to be safe. print "Escaped pattern is '$oldroot_regex'\n"; print "newdir was: '$newdir'\n"; $newdir =~ s/$oldroot_regex/$newroot/ or warn "Can't find pattern '$oldroot_regex' in dir string '$newdi +r'"; print "newdir now: '$newdir'\n\n";
Output:
Oldroot will be used as the pattern; It is 'c:\top' newdir was: 'c:\top\dir\file' Can't find pattern 'c:\top' in dir string 'c:\top\dir\file' at pm_ +790602_03.pl line 13. newdir now: 'c:\top\dir\file' Escaped pattern is 'c\:\\top' newdir was: 'c:\top\dir\file' newdir now: 'c:\newtop\dir\file'
By the way, you will save yourself some future headaches if you just standardize on POSIX paths (forward slashes instead of backslashes), which *do* work fine in Perl on Win32. I use $path =~ tr{\\}{/} to fix up user input.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://790607]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2024-04-18 16:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found