fuzzix.org

Jaws was never my scene and I don't like Star Wars
Subscribe

Perl 5 and qqw{} - Quote word with interpolation

Perl 5 has these handy quote operators to save you time, like q{} and qq{} to quote strings without and with interpolation, e.g.


0> q{"I don't have to escape quotes!"}
$res[1] = ""I don't have to escape quotes!""

It also has qw{} to create lists from quoted words. This does not interpolate variables:


1> my $message = "This is the commit message"
$res[1] = "This is the commit message"
2> qw{ git commit -m $message }
$res[2] = [
    [0] "git",
    [1] "commit",
    [2] "-m",
    [3] "$message"
]

So what if I want interpolation in my quoted word operator? qqw{}, right? Well no, but Perl 6 has qqw{}:


> my $message = "This is the commit message"
This is the commit message
> join "\n", qqw{ git commit -m $message }
git
commit
-m
This
is
the
commit
message

Hmmm, not quite what I need. Looks like what I want is qqww{}


> join "\n", qqww{ git commit -m "$message" }
git
commit
-m
This is the commit message

Perfect! Except I'm working with Perl 5. Enter Quote::Code which offers code interpolation. Variables are code, so:


3> use Quote::Code
4> qcw{ git commit -m {$message} }
$res[2] = [
    [0] "git",
    [1] "commit",
    [2] "-m",
    [3] "This is the commit message"
]

Bingo.

Shout out to freenode #perl regulars pink_mist for mentioning Quote::Code and mauke for building it in the first place!

by fuzzix on Fri, 16 Nov 2018 08:08.

Comments

Comment on this post

Text only, no HTML, * denotes a required field.

Name *
Email Address *
Website
Mystery box, leave it alone!