[Chicago-talk] Perl 101 question

Andrew Rodland arodland at comcast.net
Tue Feb 13 16:10:59 PST 2007


On Tuesday 13 February 2007 3:44 pm, Andy_Bach at wiwb.uscourts.gov wrote:
> Reviewing a beginner perl course and it says:
> [subscripting into a list]
>
> So ... I thought that was wrong but:
> print ('how', 'price', 'hat') [0];
>
> doesn't work. This does:
> my $word =  ('how', 'price', 'hat')[0];
> print "$word\n";
>
> as does:
> print "", ('how', 'price', 'hat')[0], "\n";
>
> So are the parens just to 'bind' the index to the bare list?

no, they're there to make the program make sense. While anyone who's used to 
Perl is used to calling print without parentheses, it can (like any other 
listop) be called in a form with parentheses as well (Ref: perlop, 
section "Terms and List Operators (Leftward)"). If the first thing 
after 'print' is a left-paren, then the arguments to 'print' only continue to 
the matching right-paren, just like a function call. So if you have:
	print (list)[0], "\n";
you have a call to print, with the argument (list), and then you have a [0], 
which makes no sense in what is now a TERM context, so perl throws a syntax 
error at you. The other forms you gave clarify the issue by making sure that 
the first thing after "print" isn't "(", so that it parses in the usual 
listop way. Other solutions you might see include:

	print ( (list)[0], "\n" );
or
	print +(list)[0], "\n";

Unary plus is basically a do-nothing operator that, again, makes it clear to 
the parser that print is followed by a term and not a left-paren.

Hope this helps, and as they say, hope it's FMTYEWTK!
Andrew


More information about the Chicago-talk mailing list