This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Glob.xs: Refactor iteration into separate function
[perl5.git] / ext / File-Glob / Glob.pm
1 package File::Glob;
2
3 use strict;
4 our($VERSION, @ISA, @EXPORT_OK, @EXPORT_FAIL, %EXPORT_TAGS, $DEFAULT_FLAGS);
5
6 require XSLoader;
7 use feature 'switch';
8
9 @ISA = qw(Exporter);
10
11 # NOTE: The glob() export is only here for compatibility with 5.6.0.
12 # csh_glob() should not be used directly, unless you know what you're doing.
13
14 %EXPORT_TAGS = (
15     'glob' => [ qw(
16         GLOB_ABEND
17         GLOB_ALPHASORT
18         GLOB_ALTDIRFUNC
19         GLOB_BRACE
20         GLOB_CSH
21         GLOB_ERR
22         GLOB_ERROR
23         GLOB_LIMIT
24         GLOB_MARK
25         GLOB_NOCASE
26         GLOB_NOCHECK
27         GLOB_NOMAGIC
28         GLOB_NOSORT
29         GLOB_NOSPACE
30         GLOB_QUOTE
31         GLOB_TILDE
32         glob
33         bsd_glob
34     ) ],
35 );
36
37 @EXPORT_OK   = (@{$EXPORT_TAGS{'glob'}}, 'csh_glob');
38
39 $VERSION = '1.14';
40
41 sub import {
42     require Exporter;
43     local $Exporter::ExportLevel = $Exporter::ExportLevel + 1;
44     Exporter::import(grep {
45         my $passthrough;
46         given ($_) {
47             $DEFAULT_FLAGS &= ~GLOB_NOCASE() when ':case';
48             $DEFAULT_FLAGS |= GLOB_NOCASE() when ':nocase';
49             when (':globally') {
50                 no warnings 'redefine';
51                 *CORE::GLOBAL::glob = \&File::Glob::csh_glob;
52             }
53             $passthrough = 1;
54         }
55         $passthrough;
56     } @_);
57 }
58
59 XSLoader::load();
60
61 $DEFAULT_FLAGS = GLOB_CSH();
62 if ($^O =~ /^(?:MSWin32|VMS|os2|dos|riscos)$/) {
63     $DEFAULT_FLAGS |= GLOB_NOCASE();
64 }
65
66 # File::Glob::glob() is deprecated because its prototype is different from
67 # CORE::glob() (use bsd_glob() instead)
68 sub glob {
69     splice @_, 1; # don't pass PL_glob_index as flags!
70     goto &bsd_glob;
71 }
72
73 1;
74 __END__
75
76 =head1 NAME
77
78 File::Glob - Perl extension for BSD glob routine
79
80 =head1 SYNOPSIS
81
82   use File::Glob ':glob';
83
84   @list = bsd_glob('*.[ch]');
85   $homedir = bsd_glob('~gnat', GLOB_TILDE | GLOB_ERR);
86
87   if (GLOB_ERROR) {
88     # an error occurred reading $homedir
89   }
90
91   ## override the core glob (CORE::glob() does this automatically
92   ## by default anyway, since v5.6.0)
93   use File::Glob ':globally';
94   my @sources = <*.{c,h,y}>;
95
96   ## override the core glob, forcing case sensitivity
97   use File::Glob qw(:globally :case);
98   my @sources = <*.{c,h,y}>;
99
100   ## override the core glob forcing case insensitivity
101   use File::Glob qw(:globally :nocase);
102   my @sources = <*.{c,h,y}>;
103
104   ## glob on all files in home directory
105   use File::Glob ':globally';
106   my @sources = <~gnat/*>;
107
108 =head1 DESCRIPTION
109
110 The glob angle-bracket operator C<< <> >> is a pathname generator that
111 implements the rules for file name pattern matching used by Unix-like shells
112 such as the Bourne shell or C shell.
113
114 File::Glob::bsd_glob() implements the FreeBSD glob(3) routine, which is
115 a superset of the POSIX glob() (described in IEEE Std 1003.2 "POSIX.2").
116 bsd_glob() takes a mandatory C<pattern> argument, and an optional
117 C<flags> argument, and returns a list of filenames matching the
118 pattern, with interpretation of the pattern modified by the C<flags>
119 variable.
120
121 Since v5.6.0, Perl's CORE::glob() is implemented in terms of bsd_glob().
122 Note that they don't share the same prototype--CORE::glob() only accepts
123 a single argument.  Due to historical reasons, CORE::glob() will also
124 split its argument on whitespace, treating it as multiple patterns,
125 whereas bsd_glob() considers them as one pattern.
126
127 =head2 META CHARACTERS
128
129   \       Quote the next metacharacter
130   []      Character class
131   {}      Multiple pattern
132   *       Match any string of characters
133   ?       Match any single character
134   ~       User name home directory
135
136 The metanotation C<a{b,c,d}e> is a shorthand for C<abe ace ade>.  Left to
137 right order is preserved, with results of matches being sorted separately
138 at a low level to preserve this order. As a special case C<{>, C<}>, and
139 C<{}> are passed undisturbed.
140
141 =head2 POSIX FLAGS
142
143 The POSIX defined flags for bsd_glob() are:
144
145 =over 4
146
147 =item C<GLOB_ERR>
148
149 Force bsd_glob() to return an error when it encounters a directory it
150 cannot open or read.  Ordinarily bsd_glob() continues to find matches.
151
152 =item C<GLOB_LIMIT>
153
154 Make bsd_glob() return an error (GLOB_NOSPACE) when the pattern expands
155 to a size bigger than the system constant C<ARG_MAX> (usually found in
156 limits.h).  If your system does not define this constant, bsd_glob() uses
157 C<sysconf(_SC_ARG_MAX)> or C<_POSIX_ARG_MAX> where available (in that
158 order).  You can inspect these values using the standard C<POSIX>
159 extension.
160
161 =item C<GLOB_MARK>
162
163 Each pathname that is a directory that matches the pattern has a slash
164 appended.
165
166 =item C<GLOB_NOCASE>
167
168 By default, file names are assumed to be case sensitive; this flag
169 makes bsd_glob() treat case differences as not significant.
170
171 =item C<GLOB_NOCHECK>
172
173 If the pattern does not match any pathname, then bsd_glob() returns a list
174 consisting of only the pattern.  If C<GLOB_QUOTE> is set, its effect
175 is present in the pattern returned.
176
177 =item C<GLOB_NOSORT>
178
179 By default, the pathnames are sorted in ascending ASCII order; this
180 flag prevents that sorting (speeding up bsd_glob()).
181
182 =back
183
184 The FreeBSD extensions to the POSIX standard are the following flags:
185
186 =over 4
187
188 =item C<GLOB_BRACE>
189
190 Pre-process the string to expand C<{pat,pat,...}> strings like csh(1).
191 The pattern '{}' is left unexpanded for historical reasons (and csh(1)
192 does the same thing to ease typing of find(1) patterns).
193
194 =item C<GLOB_NOMAGIC>
195
196 Same as C<GLOB_NOCHECK> but it only returns the pattern if it does not
197 contain any of the special characters "*", "?" or "[".  C<NOMAGIC> is
198 provided to simplify implementing the historic csh(1) globbing
199 behaviour and should probably not be used anywhere else.
200
201 =item C<GLOB_QUOTE>
202
203 Use the backslash ('\') character for quoting: every occurrence of a
204 backslash followed by a character in the pattern is replaced by that
205 character, avoiding any special interpretation of the character.
206 (But see below for exceptions on DOSISH systems).
207
208 =item C<GLOB_TILDE>
209
210 Expand patterns that start with '~' to user name home directories.
211
212 =item C<GLOB_CSH>
213
214 For convenience, C<GLOB_CSH> is a synonym for
215 C<GLOB_BRACE | GLOB_NOMAGIC | GLOB_QUOTE | GLOB_TILDE | GLOB_ALPHASORT>.
216
217 =back
218
219 The POSIX provided C<GLOB_APPEND>, C<GLOB_DOOFFS>, and the FreeBSD
220 extensions C<GLOB_ALTDIRFUNC>, and C<GLOB_MAGCHAR> flags have not been
221 implemented in the Perl version because they involve more complex
222 interaction with the underlying C structures.
223
224 The following flag has been added in the Perl implementation for
225 csh compatibility:
226
227 =over 4
228
229 =item C<GLOB_ALPHASORT>
230
231 If C<GLOB_NOSORT> is not in effect, sort filenames is alphabetical
232 order (case does not matter) rather than in ASCII order.
233
234 =back
235
236 =head1 DIAGNOSTICS
237
238 bsd_glob() returns a list of matching paths, possibly zero length.  If an
239 error occurred, &File::Glob::GLOB_ERROR will be non-zero and C<$!> will be
240 set.  &File::Glob::GLOB_ERROR is guaranteed to be zero if no error occurred,
241 or one of the following values otherwise:
242
243 =over 4
244
245 =item C<GLOB_NOSPACE>
246
247 An attempt to allocate memory failed.
248
249 =item C<GLOB_ABEND>
250
251 The glob was stopped because an error was encountered.
252
253 =back
254
255 In the case where bsd_glob() has found some matching paths, but is
256 interrupted by an error, it will return a list of filenames B<and>
257 set &File::Glob::ERROR.
258
259 Note that bsd_glob() deviates from POSIX and FreeBSD glob(3) behaviour
260 by not considering C<ENOENT> and C<ENOTDIR> as errors - bsd_glob() will
261 continue processing despite those errors, unless the C<GLOB_ERR> flag is
262 set.
263
264 Be aware that all filenames returned from File::Glob are tainted.
265
266 =head1 NOTES
267
268 =over 4
269
270 =item *
271
272 If you want to use multiple patterns, e.g. C<bsd_glob("a* b*")>, you should
273 probably throw them in a set as in C<bsd_glob("{a*,b*}")>.  This is because
274 the argument to bsd_glob() isn't subjected to parsing by the C shell.
275 Remember that you can use a backslash to escape things.
276
277 =item *
278
279 On DOSISH systems, backslash is a valid directory separator character.
280 In this case, use of backslash as a quoting character (via GLOB_QUOTE)
281 interferes with the use of backslash as a directory separator. The
282 best (simplest, most portable) solution is to use forward slashes for
283 directory separators, and backslashes for quoting. However, this does
284 not match "normal practice" on these systems. As a concession to user
285 expectation, therefore, backslashes (under GLOB_QUOTE) only quote the
286 glob metacharacters '[', ']', '{', '}', '-', '~', and backslash itself.
287 All other backslashes are passed through unchanged.
288
289 =item *
290
291 Win32 users should use the real slash.  If you really want to use
292 backslashes, consider using Sarathy's File::DosGlob, which comes with
293 the standard Perl distribution.
294
295 =item *
296
297 Mac OS (Classic) users should note a few differences. Since
298 Mac OS is not Unix, when the glob code encounters a tilde glob (e.g.
299 ~user) and the C<GLOB_TILDE> flag is used, it simply returns that
300 pattern without doing any expansion.
301
302 Glob on Mac OS is case-insensitive by default (if you don't use any
303 flags). If you specify any flags at all and still want glob
304 to be case-insensitive, you must include C<GLOB_NOCASE> in the flags.
305
306 The path separator is ':' (aka colon), not '/' (aka slash). Mac OS users
307 should be careful about specifying relative pathnames. While a full path
308 always begins with a volume name, a relative pathname should always
309 begin with a ':'.  If specifying a volume name only, a trailing ':' is
310 required.
311
312 The specification of pathnames in glob patterns adheres to the usual Mac
313 OS conventions: The path separator is a colon ':', not a slash '/'. A
314 full path always begins with a volume name. A relative pathname on Mac
315 OS must always begin with a ':', except when specifying a file or
316 directory name in the current working directory, where the leading colon
317 is optional. If specifying a volume name only, a trailing ':' is
318 required. Due to these rules, a glob like E<lt>*:E<gt> will find all
319 mounted volumes, while a glob like E<lt>*E<gt> or E<lt>:*E<gt> will find
320 all files and directories in the current directory.
321
322 Note that updirs in the glob pattern are resolved before the matching begins,
323 i.e. a pattern like "*HD:t?p::a*" will be matched as "*HD:a*". Note also,
324 that a single trailing ':' in the pattern is ignored (unless it's a volume
325 name pattern like "*HD:"), i.e. a glob like E<lt>:*:E<gt> will find both
326 directories I<and> files (and not, as one might expect, only directories).
327 You can, however, use the C<GLOB_MARK> flag to distinguish (without a file
328 test) directory names from file names.
329
330 If the C<GLOB_MARK> flag is set, all directory paths will have a ':' appended.
331 Since a directory like 'lib:' is I<not> a valid I<relative> path on Mac OS,
332 both a leading and a trailing colon will be added, when the directory name in
333 question doesn't contain any colons (e.g. 'lib' becomes ':lib:').
334
335 =back
336
337 =head1 SEE ALSO
338
339 L<perlfunc/glob>, glob(3)
340
341 =head1 AUTHOR
342
343 The Perl interface was written by Nathan Torkington E<lt>gnat@frii.comE<gt>,
344 and is released under the artistic license.  Further modifications were
345 made by Greg Bacon E<lt>gbacon@cs.uah.eduE<gt>, Gurusamy Sarathy
346 E<lt>gsar@activestate.comE<gt>, and Thomas Wegner
347 E<lt>wegner_thomas@yahoo.comE<gt>.  The C glob code has the
348 following copyright:
349
350     Copyright (c) 1989, 1993 The Regents of the University of California.
351     All rights reserved.
352
353     This code is derived from software contributed to Berkeley by
354     Guido van Rossum.
355
356     Redistribution and use in source and binary forms, with or without
357     modification, are permitted provided that the following conditions
358     are met:
359
360     1. Redistributions of source code must retain the above copyright
361        notice, this list of conditions and the following disclaimer.
362     2. Redistributions in binary form must reproduce the above copyright
363        notice, this list of conditions and the following disclaimer in the
364        documentation and/or other materials provided with the distribution.
365     3. Neither the name of the University nor the names of its contributors
366        may be used to endorse or promote products derived from this software
367        without specific prior written permission.
368
369     THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
370     ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
371     IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
372     ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
373     FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
374     DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
375     OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
376     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
377     LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
378     OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
379     SUCH DAMAGE.
380
381 =cut