Using the Perl qw() function
Introduction
The ‘quote word’ function qw()
is used to generate a list of words. If takes a string such as:
and returns a quoted list:
saving you from the tedium of having to quote and comma-separate each element
of the list by hand. Here’s a full example:
This code fragment has the effect of importing the tempfile
and tempdir
functions from the File::Temp
module. It does this by providing the
list 'tempfile', 'tempdir'
to the use
function.
How it works
qw()
extracts words out of your string using embedded
whitsepace as the delimiter and returns the words as a list. Note that this
happens at compile time, which means that the call to qw()
is replaced with
the list before your code starts executing.
Convenience
The qw()
function is one of the many ways in which Perl helps to make
it easier to write code. Wherever you need to construct a list like this:
you can use qw
to do the same thing more simply:
Delimeters
You can use any non-alphanumeric, non-whitespace delimeter to surround the
qw()
string argument. You’ll often see qw//
, for example.
If you use any of the bracketing characters
(
, <
, [
or {
as your delimeter, you’ll have to close with a
matching bracket.
So the following are equivalent:
Additionlly, no interpolation is possible in the string you pass to qw()
.
This code fragment:
Will output:
Quotes as operators
In Perl, quotes are considered operators. We have dealt with qw()
here as if it was a function, (and indeed it is listed as such
in the standard perlfunc documentation), but this is not the whole story.
In order to get a better picture of the subtlety of Perl’s quoting,
see the following section in the perlop documentation: