[Melbourne-pm] Referencing an item in a list
Paul Fenwick
pjf at perltraining.com.au
Sun Mar 26 20:49:07 PST 2006
G'day Brad/MPM,
Bradley Dean wrote:
> But it turns out (bring on printf parameter parsing wierdness I say) that
> I needed another set of parens (just keep adding them until something
> works could be a moral here... :)
>
> print ((gimme_an_array())[2]);
Oh! You've been caught by the rule that says whenever Perl sees parens
following a subroutine or function call, those params are always used as the
argument list. So:
print ( gimme_an_array() )[2]; OR
print (2+3)*7;
are interpreted as:
( print(gimme_an_array()) )[2]; OR
( print(2+3) ) * 7;
which certainly isn't what you want.
One possible way of fixing this is to use the unary plus operator, which stops
the parens appearing directly after the function name:
print +( gimme_an_array() )[2] OR
print +(2+3)*7;
The other, of course, is to add more parens. I usually prefer adding extra
parens because it means that more novice coders can understand what's going on.
Unary plus isn't exactly a commonly seen operator.
Cheerio,
Paul
--
Paul Fenwick <pjf at perltraining.com.au> | http://perltraining.com.au/
Director of Training | Ph: +61 3 9354 6001
Perl Training Australia | Fax: +61 3 9354 2681
More information about the Melbourne-pm
mailing list