$directory =~ s<^/*> . ; #### $directory =~ s< ^ /? # match leading '/' if present ( # capture what is between ends [^/]* # match anything not a '/' (?: # might be a '/', (?! /$ ) # but don't allow a '/' at EOL . # okay, eat the '/' ) * ) /? $ # match trailing '/' > x; # now surround the middle with '/'