12.2. Globbing

The shell (or whatever your command-line interpreter is) takes a solitary asterisk (*) command-line argument and turns it into a list of all of the filenames in the current directory. So, when you say rm *, you'll remove all of the files from the current directory. (Don't try this unless you like irritating your system administrator when you request the files to be restored.) Similarly, [a-m]*.c as a command-line argument turns into a list of all filenames in the current directory that begin with a letter in the first half of the alphabet and end in .c, and /etc/host* is a list of all filenames that begin with host in the directory /etc. (If this is new to you, you probably want to read some more about shell scripting somewhere else before proceeding.)

The expansion of arguments like * or /etc/host* into the list of matching filenames is called globbing. Perl supports globbing through a very simple mechanism: just put the globbing pattern between angle brackets or use the more mnemonically named glob function.

@a = </etc/host*>;
@a = glob("/etc/host*");

In a list context, as demonstrated here, the glob returns a list of all names that match the pattern (as if the shell had expanded the glob arguments) or an empty list if none match. In a scalar context, the next name that matches is returned, or undef is returned if there are no more matches; this is very similar to reading from a filehandle. For example, to look at one name at a time:

while (defined($nextname ...

Get Learning Perl, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.