Do you know where your variables are? | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Perl Idioms Explained - ${\$obj->method} and @{[sort @list]}
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, qr//), or perhaps, desired. So what one can do is take advantage of the perl's ${} and @{} syntax. Given the above examples I'll explain how this can be done. The notable part of the above statement is @{[ %hash ]}. Here we're creating an anonymous array containing the elements of the aptly named hash %hash. Now that we have an array reference the @{} will dereference it and the resulting array will be interpolated into the string. Simple as that! As you can probably guess what we're interested in is ${ \$obj->method }. Firstly, we call the method on an object in the standard fashion - $obj->method, 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. While the above may 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 ${\MATCHES} which calls the constant MATCHES, 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! Caveats One must be careful with the ${\foo} because if foo 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. Summary A shortcut for interpolating the return of complex expressions into a string.
_________
|
|