6.11.3 Parsing File Names: File::Basename Module

6.11.3  Parsing File Names: File::Basename Module

 

The File::Basename module allows us to parse file names easily. Of course, we can write our own regular expression to parse a file name and get the components out of it. However, things become a little difficult if we want to do it correctly all the time and across platforms. The formats used are different in systems such as Unix, Windows and Macintosh OS 9, for specifying full path names. The File::Basename module comes to our help. The following program prompts for a file name and prints its base name and the directory path preceding the base name. The base name is the name of the actual file.

 Program 6.19

#!/usr/bin/perl
#file basename.pl   

use File::Basename;
use strict;

my ($file, $basename, $dirname);

while (1){
      print "Give me a file name: ";
      $file = ;
      chomp $file; 
 
      $basename = File::Basename::basename ($file);
      $dirname = File::Basename::dirname ($file);
      print "base name = $basename; path = $dirname\n";
    }

The basename function parses the file name and gives the actual name of the file. The dirname method gives the path up to the actual file name. Here is a small interaction with this program.

 

%basename.pl

Give me a file name: abc.html

base name = abc.html; path = .

Give me a file name: /a/b/abc.html

base name = abc.html; path = /a/b

Give me a file name: /usr/home/public_html/work/cs509.html

base name = cs509.html; path = /usr/home/public_html/work

Give me a file name: /usr/home/public_html/work/

base name = ; path = /usr/home/public_html

Give me a file name:

 

The program usually works, but messes up if the directory name separator which happens to be / in Unix, is the last character in the name. Thus, for it to work, we should pre-process the name given so that it works all the time. Here, an error occurs in the last example.