azaria has asked for the wisdom of the Perl Monks concerning the following question:

Hello,
I have a problem in substitute 2 directory names, for e.g:
$dir1="D:\\Windows\\programs1"; $dir2="D:\\Windows\\programs2"; $file1 = ="D:\\Windows\\programs1\\a.txt"; ($file2 = $file1) =~ s/$dir1/$dir2/esg; print "file1 -> $file1\n"; print "file2 -> $file2\n";
I expect to get -
file1 -> D:\Windows\programs1\a.txt file2 -> D:\Windows\programs2\a.txt
but i got -
file1 -> D:\Windows\programs1\a.txt file2 -> D:\Windows\programs1\a.txt
Any idea ?

Thanks in advance

azaria

Replies are listed 'Best First'.
Re: problem in substitution
by ccn (Vicar) on Dec 08, 2008 at 07:31 UTC
    ($file2 = $file1) =~ s/\Q$dir1/$dir2/;

    Since you have backslahes inside of the pattern you need use \Q to disable pattern metacharacters.

    Also you don't need any modifiers (esg) for the regexp, excepting i probably.

    see perldoc perlre

Re: problem in substitution
by poolpi (Hermit) on Dec 08, 2008 at 09:00 UTC

    Portably perform operations on file names

    This core module may help you : File::Spec

    #for example my ($volume,$directories,$file) = File::Spec->splitpath( $path, $no_file );


    hth,
    PooLpi

    'Ebry haffa hoe hab im tik a bush'. Jamaican proverb
Re: problem in substitution
by rminner (Chaplain) on Dec 08, 2008 at 13:16 UTC
    Just like poolpi said, File::Spec is the way to go. Substituting a directory segment of a path can be annoying, because paths tend to be specified in different formats. For example: File::Find under windows returns the results with a slash appended, even though the path was specified using backslashes. In such cases you have a mixed syntax of slashes and backslashes. If you use File::Spec, you won't have to worry about the specific syntax of a path. Example:
    use File::Spec; # Example with mixed syntax my $old_dir = "D:\\Windows\\programs1"; my $new_dir = "D:\\Windows/programs2"; my $old_fn = "D:/Windows/programs1/a.txt"; my $rel_path = File::Spec->abs2rel($old_fn, $old_dir); my $new_fn = File::Spec->catfile($new_dir , $rel_path); print "New Filename: $new_fn\n"; # or combine both: my $new_fn2 = File::Spec->catfile($new_dir , File::Spec->abs2rel($old_ +fn, $old_dir)); print "New Filename2: $new_fn2\n";
Re: problem in substitution
by spmlingam (Scribe) on Dec 08, 2008 at 10:56 UTC
    If you want to enable the pattern meta characters in the regular expression again, you can use \E (\Q will disable pattern metacharacters till \E.)