Firstly, I agree with others that it would be preferable to deal with the problem at the source,
rather than fixing it within your code.
It's entirely possible that you'll need to repeat exactly the same fix in multiple scripts, modules or subroutines.
If that's not possible, it may be insufficient to just add a ^ anchor and remove the g option.
What about hidden files (e.g. .bashrc) or places where intentionally specifying the current directory is necessary.
You may need something closer to
s{^[.](?=/root(?:/|$))}{}
Consider this SSCCE:
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
my @tests = (
[qw{./root /root}],
[qw{./root/ /root/}],
[qw{./root/xyz /root/xyz}],
[qw{./root_plus ./root_plus}],
[qw{./not_root/ ./not_root/}],
[qw{./script_not_in_path.pl ./script_not_in_path.pl}],
[qw{.hidden .hidden}],
);
plan tests => 0+@tests;
for my $test (@tests) {
my $file = $test->[0];
$file =~ s{^[.](?=/root(?:/|$))}{};
is $file, $test->[1];
}
Output:
1..7
ok 1
ok 2
ok 3
ok 4
ok 5
ok 6
ok 7
That's just an example.
Modify the test cases to better reflect your real data.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.