perlmeditation
broquaint
<b>Perl Idioms Explained - <tt>${\$obj->method}</tt> and <tt>@{[sort @list]}</tt></b>
<p/>
<code>
use constant MATCHES => join '|' => qw/ a list of words /;
sub method { return "something complex here" }
my $obj = bless [];
my %hash = qw/ this is a hash /;
print "it's a hash - @{[ %hash ]}\n";
print "method result - ${ \$obj->method }\n";
print "a regexp object - ", qr[\b (?: ${\MATCHES} ) \b]x, $/;
__output__
it's a hash - this is a hash
method result - something complex here
a regexp object - (?x-ism:\b (?: a|list|of|words ) \b)
</code>
At times you'll want to add something more complex to an interpolated quote-like
than a simple variable, but the option of simply concatenating isn't
always available (i.e here docs, <tt>qr//</tt>), or perhaps, desired. So what
one can do is take advantage of the perl's <tt>${}</tt> and <tt>@{}</tt> syntax.
Given the above examples I'll explain how this can be done.
<blockquote><code>
print "it's a hash - @{[ %hash ]}\n";
</code></blockquote>
The notable part of the above statement is <tt>@{[ %hash ]}</tt>. Here
we're creating an anonymous array containing the elements of the aptly named
hash <tt>%hash</tt>. Now that we have an array reference the <tt>@{}</tt> will
dereference it and the resulting array will be interpolated into the string.
Simple as that!
<blockquote><code>
print "method result - ${ \$obj->method }\n";
</code></blockquote>
As you can probably guess what we're interested in is <tt>${ \$obj->method
}</tt>. Firstly, we call the method on an object in the standard fashion -
<tt>$obj->method</tt>, then we create a reference to what has just been
returned and finally we dereference the newly created reference and the
resulting scalar is interpolated.
<blockquote><code>
print "a regexp object - ", qr[\b (?: ${\MATCHES} ) \b]x, $/;
</code></blockquote>
While the above <i>may</i> look more complex it's just the same as the previous
example, but surrounded by a regexp string constructor. In this case we're
looking at <tt>${\MATCHES}</tt> which calls the constant <tt>MATCHES</tt>, this
returns a string which we create a reference to, then promptly dereference and
interpolate into the string, and just like that we have a constant in a regex!
<p/>
<b>Caveats</b>
<p/>
One must be careful with the <tt>${\foo}</tt> because if <tt>foo</tt> returns
something that isn't a simple scalar value then you might get unexpected
results. Also keep in mind that this is different from passing in a
simple bareword which is largely used to distinguish between variable names and
the surrounding text.
<p/>
<b>Summary</b>
<p/>
A shortcut for interpolating the return of complex expressions into a string.
<p/>
<tt>_________<br><u>broquaint</u></tt>