b904a529bdcb80dc3c67084cb5552c42eca18117
[p5sagit/p5-mst-13.2.git] / lib / File / Basename.pm
1 package File::Basename;
2
3 =head1 NAME
4
5 fileparse - split a pathname into pieces
6
7 basename - extract just the filename from a path
8
9 dirname - extract just the directory from a path
10
11 =head1 SYNOPSIS
12
13     use File::Basename;
14
15     ($name,$path,$suffix) = fileparse($fullname,@suffixlist)
16     fileparse_set_fstype($os_string);
17     $basename = basename($fullname,@suffixlist);
18     $dirname = dirname($fullname);
19
20     ($name,$path,$suffix) = fileparse("lib/File/Basename.pm","\.pm");
21     fileparse_set_fstype("VMS");
22     $basename = basename("lib/File/Basename.pm",".pm");
23     $dirname = dirname("lib/File/Basename.pm");
24
25 =head1 DESCRIPTION
26
27 These routines allow you to parse file specifications into useful
28 pieces using the syntax of different operating systems.
29
30 =over 4
31
32 =item fileparse_set_fstype
33
34 You select the syntax via the routine fileparse_set_fstype().
35 If the argument passed to it contains one of the substrings
36 "VMS", "MSDOS", "MacOS" or "AmigaOS", the file specification 
37 syntax of that operating system is used in future calls to 
38 fileparse(), basename(), and dirname().  If it contains none of
39 these substrings, UNIX syntax is used.  This pattern matching is
40 case-insensitive.  If you've selected VMS syntax, and the file
41 specification you pass to one of these routines contains a "/",
42 they assume you are using UNIX emulation and apply the UNIX syntax
43 rules instead, for that function call only.
44
45 If you haven't called fileparse_set_fstype(), the syntax is chosen
46 by examining the builtin variable C<$^O> according to these rules.
47
48 =item fileparse
49
50 The fileparse() routine divides a file specification into three
51 parts: a leading B<path>, a file B<name>, and a B<suffix>.  The
52 B<path> contains everything up to and including the last directory
53 separator in the input file specification.  The remainder of the input
54 file specification is then divided into B<name> and B<suffix> based on
55 the optional patterns you specify in C<@suffixlist>.  Each element of
56 this list is interpreted as a regular expression, and is matched
57 against the end of B<name>.  If this succeeds, the matching portion of
58 B<name> is removed and prepended to B<suffix>.  By proper use of
59 C<@suffixlist>, you can remove file types or versions for examination.
60
61 You are guaranteed that if you concatenate B<path>, B<name>, and
62 B<suffix> together in that order, the result will denote the same
63 file as the input file specification.
64
65 =back
66
67 =head1 EXAMPLES
68
69 Using UNIX file syntax:
70
71     ($base,$path,$type) = fileparse('/virgil/aeneid/draft.book7',
72                                     '\.book\d+');
73
74 would yield
75
76     $base eq 'draft'
77     $path eq '/virgil/aeneid/',
78     $type eq '.book7'
79
80 Similarly, using VMS syntax:
81
82     ($name,$dir,$type) = fileparse('Doc_Root:[Help]Rhetoric.Rnh',
83                                    '\..*');
84
85 would yield
86
87     $name eq 'Rhetoric'
88     $dir  eq 'Doc_Root:[Help]'
89     $type eq '.Rnh'
90
91 =item C<basename>
92
93 The basename() routine returns the first element of the list produced
94 by calling fileparse() with the same arguments, except that it always
95 quotes metacharacters in the given suffixes.  It is provided for
96 programmer compatibility with the UNIX shell command basename(1).
97
98 =item C<dirname>
99
100 The dirname() routine returns the directory portion of the input file
101 specification.  When using VMS or MacOS syntax, this is identical to the
102 second element of the list produced by calling fileparse() with the same
103 input file specification.  (Under VMS, if there is no directory information
104 in the input file specification, then the current default device and
105 directory are returned.)  When using UNIX or MSDOS syntax, the return
106 value conforms to the behavior of the UNIX shell command dirname(1).  This
107 is usually the same as the behavior of fileparse(), but differs in some
108 cases.  For example, for the input file specification F<lib/>, fileparse()
109 considers the directory name to be F<lib/>, while dirname() considers the
110 directory name to be F<.>).
111
112 =cut
113
114 require 5.002;
115 require Exporter;
116 @ISA = qw(Exporter);
117 @EXPORT = qw(fileparse fileparse_set_fstype basename dirname);
118 #use strict;
119 #use vars qw($VERSION $Fileparse_fstype $Fileparse_fgcase);
120 $VERSION = "2.4";
121
122
123 #   fileparse_set_fstype() - specify OS-based rules used in future
124 #                            calls to routines in this package
125 #
126 #   Currently recognized values: VMS, MSDOS, MacOS, os2, AmigaOS
127 #       Any other name uses Unix-style rules
128
129 sub fileparse_set_fstype {
130   my @old = ($Fileparse_fstype, $Fileparse_fgcase);
131   if (@_) {
132     $Fileparse_fstype = $_[0];
133     $Fileparse_fgcase = ($_[0] =~ /^(?:MacOS|VMS|os2|AmigaOS)/i);
134   }
135   wantarray ? @old : $old[0];
136 }
137
138 #   fileparse() - parse file specification
139 #
140 #   Version 2.4  27-Sep-1996  Charles Bailey  bailey@genetics.upenn.edu
141
142
143 sub fileparse {
144   my($fullname,@suffices) = @_;
145   my($fstype,$fgcase) = ($Fileparse_fstype, $Fileparse_fgcase);
146   my($dirpath,$tail,$suffix,$basename);
147
148   if ($fstype =~ /^VMS/i) {
149     if ($fullname =~ m#/#) { $fstype = '' }  # We're doing Unix emulation
150     else {
151       ($dirpath,$basename) = ($fullname =~ /^(.*[:>\]])?(.*)/);
152     }
153   }
154   if ($fstype =~ /^MSDOS/i) {
155     ($dirpath,$basename) = ($fullname =~ /^(.*[:\\\/])?(.*)/);
156     $dirpath .= '.\\' unless $dirpath =~ /[\\\/]$/;
157   }
158   elsif ($fstype =~ /^MacOS/i) {
159     ($dirpath,$basename) = ($fullname =~ /^(.*:)?(.*)/);
160   }
161   elsif ($fstype =~ /^AmigaOS/i) {
162     ($dirpath,$basename) = ($fullname =~ /(.*[:\/])?(.*)/);
163   }
164   elsif ($fstype !~ /^VMS/i) {  # default to Unix
165     ($dirpath,$basename) = ($fullname =~ m#^(.*/)?(.*)#);
166     $dirpath = './' unless $dirpath;
167   }
168
169   if (@suffices) {
170     $tail = '';
171     foreach $suffix (@suffices) {
172       my $pat = ($fgcase ? '(?i)' : '') . "($suffix)\$";
173       if ($basename =~ s/$pat//) {
174         $tail = $1 . $tail;
175       }
176     }
177   }
178
179   wantarray ? ($basename,$dirpath,$tail) : $basename;
180 }
181
182
183 #   basename() - returns first element of list returned by fileparse()
184
185 sub basename {
186   my($name) = shift;
187   (fileparse($name, map("\Q$_\E",@_)))[0];
188 }
189
190
191 #    dirname() - returns device and directory portion of file specification
192 #        Behavior matches that of Unix dirname(1) exactly for Unix and MSDOS
193 #        filespecs except for names ending with a separator, e.g., "/xx/yy/".
194 #        This differs from the second element of the list returned
195 #        by fileparse() in that the trailing '/' (Unix) or '\' (MSDOS) (and
196 #        the last directory name if the filespec ends in a '/' or '\'), is lost.
197
198 sub dirname {
199     my($basename,$dirname) = fileparse($_[0]);
200     my($fstype) = $Fileparse_fstype;
201
202     if ($fstype =~ /VMS/i) { 
203         if ($_[0] =~ m#/#) { $fstype = '' }
204         else { return $dirname || $ENV{DEFAULT} }
205     }
206     if ($fstype =~ /MacOS/i) { return $dirname }
207     elsif ($fstype =~ /MSDOS/i) { 
208         $dirname =~ s/([^:])[\\\/]*$/$1/;
209         unless( length($basename) ) {
210             ($basename,$dirname) = fileparse $dirname;
211             $dirname =~ s/([^:])[\\\/]*$/$1/;
212         }
213     }
214     elsif ($fstype =~ /AmigaOS/i) {
215         if ( $dirname =~ /:$/) { return $dirname }
216         chop $dirname;
217         $dirname =~ s#[^:/]+$## unless length($basename);
218     }
219     else { 
220         $dirname =~ s:(.)/*$:$1:;
221         unless( length($basename) ) {
222             local($File::Basename::Fileparse_fstype) = $fstype;
223             ($basename,$dirname) = fileparse $dirname;
224             $dirname =~ s:(.)/*$:$1:;
225         }
226     }
227
228     $dirname;
229 }
230
231 fileparse_set_fstype $^O;
232
233 1;