Tweet

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:

    tempfile tempdir

and returns a quoted list:

    'tempfile', 'tempdir'

saving you from the tedium of having to quote and comma-separate each element of the list by hand. Here's a full example:

    #!/usr/bin/perl
    use strict;
    use warnings;
    use File::Temp qw(tempfile tempdir);

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 whitespace 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:

    my @names = ('Kernighan', 'Ritchie', 'Pike');

you can use qw to do the same thing more simply:

    my @names = qw(Kernighan Ritchie Pike);

Delimeters

You can use any non-alphanumeric, non-whitespace delimiter to surround the qw() string argument. You'll often see qw//, for example.

If you use any of the bracketing characters (, <, [ or { as your delimiter, you'll have to close with a matching bracket.

So the following are equivalent:

    @names = qw(Kernighan Ritchie Pike);
    @names = qw/Kernighan Ritchie Pike/;
    @names = qw'Kernighan Ritchie Pike';
    @names = qw{Kernighan Ritchie Pike};

Additionally, no interpolation is possible in the string you pass to qw().

This code fragment:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $developer = 'Thompson';
    my @names = qw(Kernighan Ritchie Pike $developer);
    foreach my $name (@names) {
        print "name: $name\n";
    }

Will output:

    name: Kernighan
    name: Ritchie
    name: Pike
    name: $developer

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:

    Quote and Quote-like Operators
    Regexp Quote-Like Operators

See also

  perldoc perlfunc
[Top]