For what it's worth, it does also work with lexical variables, but you need to declare them up-front...
use v5.10;
use strict;
use warnings;
sub delayed (&) {
package delayed;
use overload q[""] => sub { $_[0]->() }, fallback => 1;
bless shift;
}
my ($person, $thing);
my $string = delayed {"Look $person, no $thing!"};
$person = "Ma";
$thing = "stringy eval";
say $string;
Here's a version that eliminates the need to declare variables up-front, but does the interpolation manually using s///eg. It's pretty dodgy, and I wouldn't put it anywhere near production code, but it's quite cute as an example...
use v5.10;
use strict;
use warnings;
use PerlX::QuoteOperator delayed => {
-emulate => 'q',
-with => sub ($) {
package delayed;
my $str = shift;
use PadWalker;
use overload q[""] => sub { $_[0]->() }, fallback => 1;
my $get = sub {
my $var = shift;
my $my = PadWalker::peek_my(3);
return $my->{$var} if exists $my->{$var};
my $our = PadWalker::peek_our(3);
return $our->{$var} if exists $our->{$var};
die "No such variable: $var\n";
};
bless sub {
my $_ = $str;
s/(\$\w+)/${$get->($1)}/eg;
s/(\@\w+)/join $", @{$get->($1)}/eg;
return $_;
};
},
};
my $string = delayed "Look $person, no @thing!";
my $person = "Ma";
my @thing = qw( stringy eval );
say $string;
It's cute, but the code that does the interpolation is pretty dodgy.
package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.