use File::Basename; my $d = "/home/temp/login"; my @b = (); while ($d ne dirname($d)) { # as long as we can move up directory tree, when we are at root the dirname won't change any more push @b, basename($d); $d = dirname($d) } print join "\n", reverse(@b)