in reply to Help with regex using variables

I would recommend using a module for manipulating paths. File::Spec is a core module, meaning you normally don't have to install it, and Path::Class is basically a nicer interface for it that gives you objects with lots of nice features.

use File::Spec::Functions qw/abs2rel/; my $path = "C:\\Dir1\\Dir2\\Dir3\\KeepMe"; my $base = "C:\\Dir1\\Dir2\\Dir3"; print abs2rel($path, $base), "\n"; # prints "KeepMe" # - or - use Path::Class qw/dir file/; my $path = dir('C:\\','Dir1','Dir2','Dir3','KeepMe'); my $base = dir('C:\\','Dir1','Dir2','Dir3'); print $path->relative($base), "\n"; # prints "KeepMe"

This code assumes it is being run on a Windows system - if you are instead manipulating Windows pathnames on a Linux or Mac system, there are ways to do that with the above modues as well.

s/$find/$replace/eeg

BTW, why are you using /eeg here? It doesn't seem necessary. (Plus, I would also anchor the regex to the beginning of the string with ^, just in case.)

Update: You asked the same question 11 years ago: Help with Regular Expressions

Replies are listed 'Best First'.
Re^2: Help with regex using variables
by bliako (Abbot) on May 16, 2023 at 07:40 UTC

    Similarly, I would use File::Spec to construct the paths and do away with all the escaping which will be taken care by Perl in a portable way:

    use File::Spec; my $path = File::Spec->catfile("C:", "Dir1", "Dir2", "Dir3", "KeepMe") +; my $base = File::Spec->catdir("C:", "Dir1", "Dir2", "Dir3"); # or my $base = File::Spec->catdir("C:", "Dir1", "Dir2", "Dir3"); my $path = File::Spec->catfile($base, "KeepMe");