How can I get the specific name of a file stored in a particular folder using glob() function? I have a sample source code below but having different output, it rather displays the complete path of the file instead of showing only the specific file name. How can I retrieve the file name only from the path set or how can I directly access and get the specific file name? thanks!
@files = glob('/Perl/Assignment/*');
foreach $files(@files){
print "$files\n";
}
Output:
/Perl/Assignment/file1.txt
/Perl/Assignment/file2.txt
/Perl/Assignment/file3.txt
Expected output:
file1.txt
file2.txt
file3.txt
You could use File::Basename
:
use File::Basename;
my @files = glob('/Perl/Assignment/*');
foreach my $file (@files){
print basename($file), "\n";
}
It's been a part of core Perl for a long time.
(Have to use parens in this case because otherwise it thinks the "\n"
is an argument to basename
instead of print
.)