#!/usr/bin/perl use strict; use warnings; my @paths = qw{ /abc/def/ghi /wxy/z /usr/local/lib/x86_64-linux-gnu/perl/5.26.1 bin/fred somefile ./another_file }; foreach my $path (@paths) { my $root_path = ''; $root_path = $1 if ($path =~ s/^([.\/]*)(.*)/$2/); my @components = split '/',$path; while (@components) { print $root_path,join('/',@components), "\n"; pop @components; } } __END__ /abc/def/ghi /abc/def /abc /wxy/z /wxy /usr/local/lib/x86_64-linux-gnu/perl/5.26.1 /usr/local/lib/x86_64-linux-gnu/perl /usr/local/lib/x86_64-linux-gnu /usr/local/lib /usr/local /usr bin/fred bin somefile ./another_file