use strict; use warnings; # for portable path and filename operations use File::Spec; my @paths = qw( /home/units/bakery/cake.pl /home/units/bakery/pie.pl /home/units/bakery/plumcake.pl /home/units/fruitjunction/juice.pl /home/units/fruitjunction/icecream.pl /home/units/bakery/choclate.pl /home/bakery/fruitjunction/not_a_bakery.pl /home/units/foo/bar.pl ); my $current_dir = ''; foreach my $path ( @paths ) { chomp $path; # retrieve the last directory in the path my $dir = get_dir( $path ); # print a start label if this is the first path if( $current_dir eq '' ) { $current_dir = uc( $dir ); print "# $current_dir\n"; } # change labels if required if( uc( $dir ) ne $current_dir ) { print "# END $current_dir\n"; $current_dir = uc( $dir ); print "# $current_dir\n"; } print "$path\n"; } print "# END $current_dir\n"; sub get_dir { my ( $path ) = @_; # extract the directory portion of the path my ( undef, $dirs, undef ) = File::Spec->splitpath( $path ); # remove trailing directory separators $dirs = File::Spec->canonpath( $dirs ); # split the path on directory separators my @dir = File::Spec->splitdir( $dirs ); return $dir[-1]; }