terdon terdon - 5 months ago 19
Perl Question

Why does Perl's glob() function always return a file name when given a string instead of a glob?

I gave a list of globs and one string to Perl's

glob
function. The globs were treated as expected but the string is always found. For example:

$ ls
foo
$ perl -le '@files=glob("*bar"); print @files' ## prints nothing, as expected
$ perl -le '@files=glob("bar"); print @files'
bar


As you can see above, the second example prints
bar
even though no such file exists.

My first thought is that it behaves like the shell in that when no expansion is available, a glob (or something being treated as a glob) expands to itself. For example, in
csh
(awful as it is, this is what Perl's
glob()
function seems to be following, see the quote below):

% foreach n (*bar*)
foreach: No match.

% foreach n (bar)
foreach? echo $n
foreach? end
bar ## prints the string


However, according to the docs,
glob
should return filename expansions (emphasis mine):


In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell /bin/csh would do.


So why is it returning itself when there are no globbing characters in the argument passed to
glob
? Is this a bug or am I doing something wrong?

Answer

When you use ? or * or [], only existing files or directories will be returned. When you pattern just has literal text or {}, all possible results will be returned. This exactly matches what a standard shell does.

Often, people will do @results = grep -e, glob PATTERN because of this.

Or you can use File::Glob::bsd_glob if you want more control over this.