terdon terdon - 1 year ago 128
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

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

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

As you can see above, the second example prints
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
(awful as it is, this is what Perl's
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,
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
? Is this a bug or am I doing something wrong?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download