perlglobbasename

Get 'basename' from 'glob'


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.


Solution

  • 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/*");