Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

glob() function in Perl for getting filenames

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
like image 876
Raven Avatar asked Dec 24 '22 17:12

Raven


1 Answers

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.)

like image 196
Jim Davis Avatar answered Dec 27 '22 10:12

Jim Davis