I have the following:
my @path = split( "/", getcwd );
my $grandParent = $path[-2];
I’d like to do it in one line (like in other languages) since I’m not using @path again, like so:
my $grandParent = split( "/", getcwd )[-2];
Is this possible? If so, how?
EDIT: Just to be clear – where I am running the script from I know some things are going to be invariant (the directory structure, names, etc). This being said, validation is nice, but in this scenario is more clutter than it is worth; thanks to those who submitted solutions with error checking any ways.
should be:
Addendum:
another way (somehow more ‘perlish’):
(taking into account some of tchrist’s good advice)
Addendum 2:
Some comment:
Sometimes, there might not be a
$grandparentdirectory at all.If used in the root dir on a Unix system ‘/’, above will
result in:
if in a directory directly below ‘/’, eg. ‘/somedir’,
so you may check for that condition. Furthermore, the
reversereverses the order of the elements of the splitted path, so you know you
need to look at the (now) first two elements to know where you are.
Regards
rbo