On Perl


Location: Chicago/Delhi, United States

Tuesday, June 14, 2005

print Quiz

We always take printf, System.out.println, print etc to be the simplest parts of any programming language. Here is perl teaser on print:

What will the following piece of code print?
print ( 2 + 2 ) * 5 ;

Since I have told you it is a teaser, then you already know the answer is not going to be 20 i.e. 4*5. So what will it be? Will this piece of code give an error? No.

At this point, you probably want to read the perldoc on print or simply run this code.

It prints 4. The part corresponding to (2+2) only. What happens to the rest? It's all there in perldoc which says:
Also be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print--interpose a `+' or put parentheses around all the arguments.

So the arguments to print are (2+2) only, and the rest i.e. * 5, is simply ignored.


Post a Comment

<< Home