6.9 Perl glob

Brace expansion is a feature of glob that generates multiple strings by expanding expressions enclosed in {}.


1. Simple list

my @list = glob "{red,green,blue}"; # ("red", "green", "blue")

2. File extensions

my @files = glob "file.{txt,pdf,doc}"; # e.g. ("file.txt", "file.pdf", "file.doc")

3. Prefixes

my @names = glob "{Mr,Mrs,Dr}.Smith"; # ("Mr.Smith", "Mrs.Smith", "Dr.Smith")

4. Multiple brace expressions

my @list = glob "{A,B}{1,2}"; # ("A1", "A2", "B1", "B2")

5. Three brace expressions

my @list = glob "{A,B}{1,2}{x,y}"; # ("A1x", "A1y", "A2x", "A2y", "B1x", "B1y", "B2x", "B2y")

6. Binary combinations

my @bits = glob "{0,1}{0,1}{0,1}"; # ("000", "001", "010", "011", "100", "101", "110", "111") 	

7. Words

my @words = glob "{big,small}{cat,dog}"; # ("bigcat", "bigdog", "smallcat", "smalldog") 	

8. Empty alternative

my @list = glob "{,un}happy"; # ("happy", "unhappy") 	
my @list = glob "colo{,u}r"; # ("color", "colour") 

9. Combining with wildcards

my @files = glob "*.{pl,pm}"; # e.g. ("main.pl", "test.pl", "main.pm", "test.pm") 
my @files = glob("*.txt");# or: my @files = <*.txt>;

10. Processing all .pl files

# in scalar context, glob returns one match 
foreach my $file (glob("*.pl")) {
    print "Processing $file\n";
}

Summary

Expression Expands to
{A,B} ("A", "B")
{1,2,3} ("1", "2", "3")
{A,B}{1,2} ("A1", "A2", "B1", "B2")
{0,1}{0,1} ("00", "01", "10", "11")
{,u} ("", "u")
*.{pl,pm} .pl and .pm files in the current directory.