Home > Software engineering >  How can I go two level back in perl using dirname?
How can I go two level back in perl using dirname?

Time:03-24

I have a value stored in a variable

$var1="/home/PPP/Testing/dir2/file1";

and this is a real path in my linux system. Now, using the value of $var1, I want to extract the value of $var2.

I want "/home/PPP/Testing" in $var2. I can't put the string value directly in $var2 because the path in $var1 could vary. Like, it ($var1) could be "/home/PPP/Testing/dir2/file1", "/home/PPP/lnx/dir3/file4", "/home/PPP/window62/dir24/file1".

So, in all, I would want the path in $var1 to get two levels back, and then is stored in $var2.

How can I do it? Can it be done using dirname ?

CodePudding user response:

To extract a part of the path best parse the path and then reassamble what you need.

The easiest thing to recommend for parsing is a library for that job, like core File::Spec

use File::Spec;

my @fqn = File::Spec->splitdir($var1);

my $var2 = File::Spec->catdir( @fqn[0..$#fqn-2] ); 

The splitdir returns an empty first element if the path starts with a / (by design), and since you precisely want to join these back that first empty element is just as needed. And then join up to the last two elements (filename and one dir to discard). The variable $#aryname is the index of the last element in the array aryname.

There are yet other libraries of course, and then other ways.

One can manually split the path by / by my @fqn = split m{/}, $var1, where the first element is again an empty string if the path starts with /. Or use regex like my @fqn = m{[^/] }g (now the first element isn't empty). I don't see any advantages of these over a good library in this case.

CodePudding user response:

Here's an example of doing it with Path::Tiny. It's not in core Perl, but it's pretty nifty.

use Path::Tiny;

my $var1 = "/home/PPP/Testing/dir2/file1";
my $var2 = path($var1)->parent(2);
  • Related