throop has asked for the wisdom of the Perl Monks concerning the following question:

Brethren,

After studying blokhead's trick of using glob to expand wildcards (OK, I'm impressed.)

The example shows me I still don't have the hang of glob. The glob documentation says that the metacharacters behave as

\ Quote the next metacharacter [] Character class {} Multiple pattern * Match any string of characters ? Match any single character ~ User name home directory
So why does glob('foo{a,b}') expand into fooa, foob, but glob('foo[ab]') expand into nothing?

throop

Replies are listed 'Best First'.
Re: How glob expands
by Fletch (Bishop) on Sep 29, 2007 at 00:01 UTC

    Because that's the way shells do it and File::Glob (and glob as of not-so-recent versions) uses the BSD csh (I believe) globbing implementation.

    It might help to think of the character class being a predicate ("Is there a file present in the cwd which has one of these characters at the position in question?"), whereas the curly braces work more as a pattern that you're asking the globbing engine to generate irrespective of the contents of the current working directory ("Give me a list made up of items with the un-braced portion followed by each of the alternatives.").

    Yes, it's nonintuitive. But that's the way it works.

    Update: Durr, says right on the label: Post 5.6.0 glob is implemented with File::Glob, and I want to say the BSD-based C implementation was made at the same time. So glob should behave more-or-less the same way everywhere for not-unreasonably-old perls.

    Shell example: Just as way of proof, here's the way zsh (another shell which implements csh-esque globbing) behaves. Prior to the first command there's no files in the directory.

    $ zsh -c 'print foo{a,b}' fooa foob $ zsh -c 'print foo[a,b]' zsh: no matches found: foo[ab] $ touch fooa $ zsh -c 'print foo[ab]' fooa

    Just remember that [] is a predicate on directory contents, {} is dumb pattern expansion.

      Yes, glob curlies are cool and useful for things other than matching filenames. You can do stuff like this:

      $pat = join '-', ('{foo,bar,baz}') x 3; $\="\n"; print for glob $pat;
Re: How glob expands
by Joost (Canon) on Sep 28, 2007 at 23:56 UTC