http://www.perlmonks.org?node_id=509937


in reply to Regular Expression Help

Or utilize rindex: (this code works regarless whether there is a trailing /)

use strict; use warnings; { my $str = "/rootdir/sub1/sub2/sub3/sub4/"; print substr($str, 0, rindex($str, "/", length($str) - 2)); } print "\n"; { my $str = "/rootdir/sub1/sub2/sub3/sub4"; print substr($str, 0, rindex($str, "/", length($str) - 2)); }

which prints:

/rootdir/sub1/sub2/sub3 /rootdir/sub1/sub2/sub3