Take the 2-minute tour ×

I would like to remove the matching pattern starting from end of the line and store the rest of the line to a variable how do it in perl ?

For Eg :

$ROOT = "/home/usr/bin";

I want to remove "/bin" from above $ROOT variable and print/store the rest. Will the below code work ?

$ROOT =s/^(.*?)(?=\/bin)/$1/g
print $ROOT;

Will the above code print below output,


Please note I may be wrong with above suggestion as I am new. Please help me out.

share|improve this question
will it always be a directory or any string? –  amphibient Feb 28 '13 at 21:20
instead of asking "will it do this/that?", why not try it yourself? you do have access to a perl interpreter, don't you? –  amphibient Feb 28 '13 at 21:21
That's a convoluted way of doing $ROOT =~ s/\/bin$// –  Borodin Feb 28 '13 at 23:02
add comment

3 Answers

You've broken it by using a look-ahead. If you had written just

$ROOT =~ s/^(.*)\/bin/$1/

then it would work. To remove the last segment of any path, write

$ROOT =~ s|/[^/]*$||
share|improve this answer
add comment

Try this :

my $ROOT = "/home/usr/bin";
$ROOT =~ s!/bin$!!; # the delimiter is "!" to avoid escaping "/"
print $ROOT;

And like foampile said, you can test your regex with a perl interpreter. I recommend you the interactive perl shell perlconsole or re.pl

perlconsole :

enter image description here

share|improve this answer
add comment

Or you could use File::Basename:

use strict;
use warnings;
use File::Basename;

print dirname($ROOT);


share|improve this answer
+1 This is the right way to do it when dealing with file names and path names. –  squiguy Feb 28 '13 at 22:13
add comment

Your Answer


