3 File::Basename - Parse file paths into directory, filename and suffix.
9 ($name,$path,$suffix) = fileparse($fullname,@suffixlist);
10 $name = fileparse($fullname,@suffixlist);
12 $basename = basename($fullname,@suffixlist);
13 $dirname = dirname($fullname);
18 These routines allow you to parse file paths into their directory, filename
21 B<NOTE>: C<dirname()> and C<basename()> emulate the behaviours, and
22 quirks, of the shell and C functions of the same name. See each
23 function's documentation for details. If your concern is just parsing
24 paths it is safer to use L<File::Spec>'s C<splitpath()> and
25 C<splitdir()> methods.
29 # Where $path_separator is / for Unix, \ for Windows, etc...
30 dirname($path) . $path_separator . basename($path);
32 is equivalent to the original path for all systems but VMS.
38 package File::Basename;
40 # File::Basename is used during the Perl build, when the re extension may
41 # not be available, but we only actually need it if running under tainting.
53 our(@ISA, @EXPORT, $VERSION, $Fileparse_fstype, $Fileparse_igncase);
56 @EXPORT = qw(fileparse fileparse_set_fstype basename dirname);
59 fileparse_set_fstype($^O);
67 my($filename, $directories, $suffix) = fileparse($path);
68 my($filename, $directories, $suffix) = fileparse($path, @suffixes);
69 my $filename = fileparse($path, @suffixes);
71 The C<fileparse()> routine divides a file path into its $directories, $filename
72 and (optionally) the filename $suffix.
74 $directories contains everything up to and including the last
75 directory separator in the $path including the volume (if applicable).
76 The remainder of the $path is the $filename.
78 # On Unix returns ("baz", "/foo/bar/", "")
79 fileparse("/foo/bar/baz");
81 # On Windows returns ("baz", "C:\foo\bar\", "")
82 fileparse("C:\foo\bar\baz");
84 # On Unix returns ("", "/foo/bar/baz/", "")
85 fileparse("/foo/bar/baz/");
87 If @suffixes are given each element is a pattern (either a string or a
88 C<qr//>) matched against the end of the $filename. The matching
89 portion is removed and becomes the $suffix.
91 # On Unix returns ("baz", "/foo/bar/", ".txt")
92 fileparse("/foo/bar/baz.txt", qr/\.[^.]*/);
94 If type is non-Unix (see C<fileparse_set_fstype()>) then the pattern
95 matching for suffix removal is performed case-insensitively, since
96 those systems are not case-sensitive when opening existing files.
98 You are guaranteed that C<$directories . $filename . $suffix> will
99 denote the same location as the original $path.
105 my($fullname,@suffices) = @_;
107 unless (defined $fullname) {
109 Carp::croak("fileparse(): need a valid pathname");
113 my($type,$igncase) = ($Fileparse_fstype, $Fileparse_igncase);
115 my($taint) = substr($fullname,0,0); # Is $fullname tainted?
117 if ($type eq "VMS" and $fullname =~ m{/} ) {
118 # We're doing Unix emulation
123 my($dirpath, $basename);
125 if (grep { $type eq $_ } qw(MSDOS DOS MSWin32 Epoc)) {
126 ($dirpath,$basename) = ($fullname =~ /^((?:.*[:\\\/])?)(.*)/s);
127 $dirpath .= '.\\' unless $dirpath =~ /[\\\/]\z/;
129 elsif ($type eq "OS2") {
130 ($dirpath,$basename) = ($fullname =~ m#^((?:.*[:\\/])?)(.*)#s);
131 $dirpath = './' unless $dirpath; # Can't be 0
132 $dirpath .= '/' unless $dirpath =~ m#[\\/]\z#;
134 elsif ($type eq "AmigaOS") {
135 ($dirpath,$basename) = ($fullname =~ /(.*[:\/])?(.*)/s);
136 $dirpath = './' unless $dirpath;
138 elsif ($type eq 'VMS' ) {
139 ($dirpath,$basename) = ($fullname =~ /^(.*[:>\]])?(.*)/s);
140 $dirpath ||= ''; # should always be defined
142 else { # Default to Unix semantics.
143 ($dirpath,$basename) = ($fullname =~ m{^(.*/)?(.*)}s);
144 if ($orig_type eq 'VMS' and $fullname =~ m{^(/[^/]+/000000(/|$))(.*)}) {
145 # dev:[000000] is top of VMS tree, similar to Unix '/'
146 # so strip it off and treat the rest as "normal"
149 ($dirpath,$basename) = ($remainder =~ m{^(.*/)?(.*)}s);
150 $dirpath ||= ''; # should always be defined
151 $dirpath = $devspec.$dirpath;
153 $dirpath = './' unless $dirpath;
160 foreach $suffix (@suffices) {
161 my $pat = ($igncase ? '(?i)' : '') . "($suffix)\$";
162 if ($basename =~ s/$pat//s) {
163 $taint .= substr($suffix,0,0);
169 # Ensure taint is propgated from the path to its pieces.
171 wantarray ? ($basename .= $taint, $dirpath .= $taint, $tail)
172 : ($basename .= $taint);
178 X<basename> X<filename>
180 my $filename = basename($path);
181 my $filename = basename($path, @suffixes);
183 This function is provided for compatibility with the Unix shell command
184 C<basename(1)>. It does B<NOT> always return the file name portion of a
185 path as you might expect. To be safe, if you want the file name portion of
186 a path use C<fileparse()>.
188 C<basename()> returns the last level of a filepath even if the last
189 level is clearly directory. In effect, it is acting like C<pop()> for
190 paths. This differs from C<fileparse()>'s behaviour.
193 basename("/foo/bar");
194 basename("/foo/bar/");
196 @suffixes work as in C<fileparse()> except all regex metacharacters are
199 # These two function calls are equivalent.
200 my $filename = basename("/foo/bar/baz.txt", ".txt");
201 my $filename = fileparse("/foo/bar/baz.txt", qr/\Q.txt\E/);
203 Also note that in order to be compatible with the shell command,
204 C<basename()> does not strip off a suffix if it is identical to the
205 remaining characters in the filename.
213 # From BSD basename(1)
214 # The basename utility deletes any prefix ending with the last slash `/'
215 # character present in string (after first stripping trailing slashes)
216 _strip_trailing_sep($path);
218 my($basename, $dirname, $suffix) = fileparse( $path, map("\Q$_\E",@_) );
220 # From BSD basename(1)
221 # The suffix is not stripped if it is identical to the remaining
222 # characters in string.
223 if( length $suffix and !length $basename ) {
227 # Ensure that basename '/' == '/'
228 if( !length $basename ) {
229 $basename = $dirname;
240 This function is provided for compatibility with the Unix shell
241 command C<dirname(1)> and has inherited some of its quirks. In spite of
242 its name it does B<NOT> always return the directory name as you might
243 expect. To be safe, if you want the directory name of a path use
246 Only on VMS (where there is no ambiguity between the file and directory
247 portions of a path) and AmigaOS (possibly due to an implementation quirk in
248 this module) does C<dirname()> work like C<fileparse($path)>, returning just the
252 my $directories = dirname($path);
254 When using Unix or MSDOS syntax this emulates the C<dirname(1)> shell function
255 which is subtly different from how C<fileparse()> works. It returns all but
256 the last level of a file path even if the last level is clearly a directory.
257 In effect, it is not returning the directory portion but simply the path one
258 level up acting like C<chop()> for file paths.
260 Also unlike C<fileparse()>, C<dirname()> does not include a trailing slash on
263 # returns /foo/bar. fileparse() would return /foo/bar/
264 dirname("/foo/bar/baz");
266 # also returns /foo/bar despite the fact that baz is clearly a
267 # directory. fileparse() would return /foo/bar/baz/
268 dirname("/foo/bar/baz/");
270 # returns '.'. fileparse() would return 'foo/'
273 Under VMS, if there is no directory information in the $path, then the
274 current default device and directory is used.
282 my($type) = $Fileparse_fstype;
284 if( $type eq 'VMS' and $path =~ m{/} ) {
286 local($File::Basename::Fileparse_fstype) = '';
287 return dirname($path);
290 my($basename, $dirname) = fileparse($path);
292 if ($type eq 'VMS') {
293 $dirname ||= $ENV{DEFAULT};
295 elsif (grep { $type eq $_ } qw(MSDOS DOS MSWin32 OS2)) {
296 _strip_trailing_sep($dirname);
297 unless( length($basename) ) {
298 ($basename,$dirname) = fileparse $dirname;
299 _strip_trailing_sep($dirname);
302 elsif ($type eq 'AmigaOS') {
303 if ( $dirname =~ /:\z/) { return $dirname }
305 $dirname =~ s{[^:/]+\z}{} unless length($basename);
308 _strip_trailing_sep($dirname);
309 unless( length($basename) ) {
310 ($basename,$dirname) = fileparse $dirname;
311 _strip_trailing_sep($dirname);
319 # Strip the trailing path separator.
320 sub _strip_trailing_sep {
321 my $type = $Fileparse_fstype;
323 if (grep { $type eq $_ } qw(MSDOS DOS MSWin32 OS2)) {
324 $_[0] =~ s/([^:])[\\\/]*\z/$1/;
327 $_[0] =~ s{(.)/*\z}{$1}s;
332 =item C<fileparse_set_fstype>
335 my $type = fileparse_set_fstype();
336 my $previous_type = fileparse_set_fstype($type);
338 Normally File::Basename will assume a file path type native to your current
339 operating system (ie. /foo/bar style on Unix, \foo\bar on Windows, etc...).
340 With this function you can override that assumption.
342 Valid $types are "VMS", "AmigaOS", "OS2", "RISCOS",
343 "MSWin32", "DOS" (also "MSDOS" for backwards bug compatibility),
344 "Epoc" and "Unix" (all case-insensitive). If an unrecognized $type is
345 given "Unix" will be assumed.
347 If you've selected VMS syntax, and the file specification you pass to
348 one of these routines contains a "/", they assume you are using Unix
349 emulation and apply the Unix syntax rules instead, for that function
359 my @Ignore_Case = qw(VMS AmigaOS OS2 RISCOS MSWin32 MSDOS DOS Epoc);
360 my @Types = (@Ignore_Case, qw(Unix));
362 sub fileparse_set_fstype {
363 my $old = $Fileparse_fstype;
366 my $new_type = shift;
368 $Fileparse_fstype = 'Unix'; # default
369 foreach my $type (@Types) {
370 $Fileparse_fstype = $type if $new_type =~ /^$type/i;
374 (grep $Fileparse_fstype eq $_, @Ignore_Case) ? 1 : 0;
388 L<dirname(1)>, L<basename(1)>, L<File::Spec>