Since you are spliting and concatenating on forward slashes it looks like you might be dealing with *nix paths. Like Bloodnok, I'm not sure why you are changing element 4 then not using it. The following script forms @arr four different ways as I'm not sure what you intend:-
- Just the first two elements as in your code.
- The first three so that you get two path elements.
- All elements with the fourth element changed as in your code if it contains '.prn' (I have anchored to the end of string in the assumption that it is an extension).
- As above but changing the last element instead of the fourth to cope with paths with different depths.
use strict;
use warnings;
my @data = qw{
/path/some/random/file
/home/mary/projectA/reports/rep1.prn
/usr/man/man1/brewcoffee.1
/home/fred/projects/cv.prn
/home/bill/work/prog.c
};
my @arr =
sort
map { join q{/}, ( split m{/} )[ 0, 1 ] }
@data;
print qq{$_\n} for @arr;
print q{-} x 20, qq{\n};
@arr =
sort
map { join q{/}, ( split m{/} )[ 0 .. 2 ] }
@data;
print qq{$_\n} for @arr;
print q{-} x 20, qq{\n};
@arr =
sort
map { $_->[ 4 ] =~ s{.prn$}{}i ; join q{/}, @$_ }
map { [ split m{/} ] }
@data;
print qq{$_\n} for @arr;
print q{-} x 20, qq{\n};
@arr =
sort
map { $_->[ -1 ] =~ s{.prn$}{}i ; join q{/}, @$_ }
map { [ split m{/} ] }
@data;
print qq{$_\n} for @arr;
print q{-} x 20, qq{\n};
The output.
/home
/home
/home
/path
/usr
--------------------
/home/bill
/home/fred
/home/mary
/path/some
/usr/man
--------------------
/home/bill/work/prog.c
/home/fred/projects/cv
/home/mary/projectA/reports/rep1.prn
/path/some/random/file
/usr/man/man1/brewcoffee.1
--------------------
/home/bill/work/prog.c
/home/fred/projects/cv
/home/mary/projectA/reports/rep1
/path/some/random/file
/usr/man/man1/brewcoffee.1
--------------------
I hope I have guessed correctly and this is of some use to you.