print (1 ? 1 : 0) . 'x'

James Mastros james at mastros.biz
Thu May 11 12:53:49 BST 2006


On Thu, May 11, 2006 at 11:59:05AM +0100, Jonathan Stowe wrote:
> On Thu, 2006-05-11 at 10:59, O'Shaughnessy, Jamie wrote:
> > print (1 ? 1 : 0) . 'x';
> > 
> > What do you expect this would print?
> > 
> > I expected the output would be "1x" - the ?: evaluates to 1, the ()s are needed because . Is higher precedence than ?: so you end up with 1 . 'x' as the parameter to print - hence print "1x".
> > 
> > However it doesn't, it just prints "1".
> > 
> > Can anyone explain what is happening here?
> > 
> 
> As well as the switching on of warnings that everyone else is
> advocating, light can sometimes be shone on confusing behaviour by using
> B::Deparse:
> 
>         [jonathan at orpheus jonathan]$ perl -MO=Deparse
>         print (1 ? 1 : 0) . 'x';
>         __END__
>         print(1) . 'x';
>         __DATA__

Or -MO=Deparse,-p.  Sometimes the extra parens get in the way of
understanding, but just as often, they're the entire point.  (When you get
confused by the precidence of &&/||/and/or, which happens to many people
fairly often.)

In this case, it's not much help:

perl -MO=Deparse,-p -e'print (1 ? 1 : 0) . 'x';'
(print(1) . 'x');

	  -=- James Mastros


More information about the london.pm mailing list