Tim
Tim

Reputation: 14154

Is there an interpolating quote-like word list operator?

qw{} is a nice-looking way for writing lists. Is there a similar that interpolates the words, i.e. expands variables? perlop does not seem to mention any.

Upvotes: 5

Views: 2066

Answers (4)

Stefan Majewsky
Stefan Majewsky

Reputation: 5555

Expanding on ysth's answer:

sub qqw($) { split /\s+/, $_[0] }

my @list = qqw"$var interpolating string";

Caveats: I don't know how leading and trailing whitespace are handled. Furthermore, the prototype should make sure that qqw does not consume multiple comma-separated values like sub calls normally do, but you should check that to be sure.

Upvotes: 3

Sean
Sean

Reputation: 29772

You can sprinkle qw() in the midst of a "regular" list. I sometimes write code like this:

my @command = (
    qw(cat arg1 arg2),
    $arg3,
    qw(arg4 arg5 arg6),
    "$arg7 $arg8",
    # ...
);

Upvotes: 7

ysth
ysth

Reputation: 98398

Just:

split(' ', "$var interpolating string ");

Upvotes: 1

tchrist
tchrist

Reputation: 80415

No, there is no built-in, but many of us write our own.

Also for the two kinds of ql() needs for lists of lines. I use deQ for a q() version and deQQ for a qq version of those that works with Perl’s “hasta” operator:

sub dequeue($$) {
    my($leader, $body) = @_;
    $body =~ s/^\s*\Q$leader\E ?//gm;
    return $body;
}

sub deQ($) {
    my $text = $_[0];
    return dequeue q<|Q|>,  $text;
}

sub deQQ($) {
    my $text = $_[0];
    return dequeue qq<|QQ|>, $text;
}

That lets me use stuff like this:

sub compile($) {
    my $CODE = shift();
    my $wrap = deQQ<<"END_OF_COMPILATION";
                |QQ|
                |QQ|    use warnings qw[FATAL all];
                |QQ|    no  warnings "utf8";
                |QQ|
                |QQ|    sub { 
                |QQ|           my \$_ = shift; 
                |QQ|           $CODE; 
                |QQ|           return \$_;
                |QQ|    }
                |QQ|
END_OF_COMPILATION

    return eval $wrap;

} 

or

        my $sorter = new Unicode::Collate::
                            upper_before_lower  => 1,
                            preprocess          => \&reduce_for_sorting,
                            entry               => deQ<<'END_OF_OVERRIDE'
             |Q|
             |Q|        005B 006E 002E ; [.0200.0020.0002.0391] # [n.
             |Q|        005B           ; [.0220.0020.0002.0392] # [
             |Q|        005D           ; [.0225.0020.0002.0395] # ]
             |Q|
END_OF_OVERRIDE

See how that works?

Upvotes: 6

Related Questions