Home > Software design >  Get 'basename' from 'glob'
Get 'basename' from 'glob'

Time:03-25

Directory path "/home/PPP/main/windows/agile/cmPvt" has aaa, bbb, ccc, ddd as its contents.

Code Snippet:

use File::Basename;
my $kkLoc = ("/home/PPP/main/windows/agile/cmPvt");
my @kkarray = glob("$kkLoc/*") if (-e $kkLoc);
foreach my $kknum (@kkarray) {  ## Here: see below
}   

Here: here I want that in @kkarray, "aaa", "bbb", "ccc", "ddd" shall come, but I am getting the whole path like "/home/PPP/main/windows/agile/cmPvt/aaa", "/home/PPP/main/windows/agile/cmPvt/bbb",.... Also, I tried, foreach my $kknum (basename "@kkarray") { }, but not working.

How can I get the "basename" from the full path while doing glob()?

Note: I can't do chdir to the path before executing glob command due to a reason.

CodePudding user response:

You tried to use a string with the interpolated array as argument to basename. That is wrong. You should take the individual paths, not all the paths concatenated together.

for my $path (@paths) { 
    print "Basename is: ", basename($path);
}

It says in the documentation how you should use the basename function:

my $filename = basename($path);
my $filename = basename($path, @suffixes);

This function is provided for compatibility with the Unix shell command basename(1). It does NOT always return the file name portion of a path as you might expect. To be safe, if you want the file name portion of a path use fileparse().

basename() returns the last level of a filepath even if the last level is clearly directory. In effect, it is acting like pop() for paths. This differs from fileparse()'s behaviour.

# Both return "bar"
basename("/foo/bar");
basename("/foo/bar/");

You should note that by removing the full paths from the glob, that you cannot access the files if you cannot also chdir to their location, like you said you could not do "for a reason". So this whole exercise might be quite pointless for you.

You might like to look at File::Find which does a similar thing, recursively, and automatically allows you to select basename or full name. Like an all in one package.

CodePudding user response:

You can use map to call basename on each element of the array:

foreach my $kknum (map { basename($_) } @kkarray) {
}

This keeps the full path in the array variable, if that is desired.

If you never want the full path in the array variable, you can use map when you populate the array:

my @kkarray = map { basename($_) } glob("$kkLoc/*");

CodePudding user response:

If you're only ever interested in the filenames within that directory, then just read the directory directly:

my $path = '.....';
opendir my $dir, $path or die "opendir($path): $!\n";
my @kkarray = sort grep !/^\.\.?$/, readdir $dir;
close $dir;
  • Related