Is there an interpolating quote-like word list ope

2020-06-25 05:26发布

问题:

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.

回答1:

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?



回答2:

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",
    # ...
);


回答3:

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.



回答4:

Just:

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