Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,

how come

print ("a", "b")[1];
does not work (need more ()),

but

print qw(a, b)[1];
works fine ????

Code tags added by Arunbear

Replies are listed 'Best First'.
Re: print question
by mreece (Friar) on Aug 16, 2007 at 02:40 UTC
    qw() returns a list but print does not. you can make it clear to perl that ("a", "b") is its own list rather than the parameters to the print function with the unary-plus trick:
    print +("a", "b")[1];
    and to quote code in your posts, use <c>...</c>
Re: print question
by jdporter (Paladin) on Aug 16, 2007 at 02:46 UTC

    It stems from the fact that print, if immediately followed by a lparen (with \s* in between), assumes that the lparen and its matching rparent enclose print's entire parameter list. You can clear up print's "confusion" by adding another set of parens to enclose the parameter list:

    print( ("a", "b")[1] );
    A word spoken in Mind will reach its own level, in the objective world, by its own weight
Re: print question
by Anonymous Monk on Aug 16, 2007 at 02:53 UTC
    So I wanted to say that

    print ("a", "b")[1];

    does not work, you need an extra pair of ():

    print (("a", "b")[1]);

    but

    print qw(a, b)[1];

    works fine without ().

    The book I am reading(http://www.perl.org/books/beginning-perl/) says print has higher precedence than 1. But this does not work in the second example with "qw" so I am confused.

      i mean print has higher precedence than [1]. But this is not true in the second example.
        Let me try to explain the question better :

        ("a", "b") and qw(a, b)

        are two equivalent ways of defining a list, so both examples should not work(because print has higher priority than [1]):

        print ("a", "b")[1]; print qw(a, b)[1];

        But for some reason only the first one does not work...

Re: print question
by Anonymous Monk on Aug 16, 2007 at 02:31 UTC
    sorry dont know how to include square brackets here, wanted to write square brackets 1.

      From the bottom of SoPW:

      for [ use &#91;
      for ] use &#93;
      

      - Miller

        Um, yeah, but you left out the bit that says "Outside of code tags, you may need to use entities for some characters." A better answer would have been to put <code> tags around the chunks of perl code.

      Enclose code in <code> </code> tags. See the bulleted help at the bottom of the preview page (although you can use &#91; and &#93; for [ and ] if required outside a code context).


      DWIM is Perl's answer to Gödel
      thank you all for your responses!