http://www.perlmonks.org?node_id=1001781

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

Hi Monks,

Was just trying some statements and wondered why a similar one doesn't work.
print ("adf","ff","f"); # Gladly prints the list print ("adf","ff","f")[1]; #Gives a syntax error $val=("adf","ff","f")[1];print $val; #Works easily print join "",("adf","ff","f"); #Works print join "",("adf","ff","f")[1]; #Works since treated in list contex +t
I might be wrong on some basics. But why the 2nd statement fails. I mean if such a thing works, then we can directly use it to print a single element returned from a function or method(like in Java).e.g.
(sort {$a<=>} @lst)[0] # an alternative way to get min value from some + numeric list.
Similarly in Java we can do:
obj.method()[2] #when we know that method returns an array

Tried to search a little about this, but could not find a reasonable thread for the same. Sorry again if this is some conceptual weakness of mine.

Replies are listed 'Best First'.
Re: Getting single element from an array
by choroba (Cardinal) on Nov 01, 2012 at 09:20 UTC
    The ( in the second case is taken by the parser as starting the argument list. When the [ is being parsed, it is already too late to change mind. You can use + to disambiguate:
    print +("adf","ff","f")[1];
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Getting single element from an array
by Anonymous Monk on Nov 01, 2012 at 09:16 UTC
    ? What is the difference between
    print( 1,2,3 ); print( ( 1,2,3 )[1] );
    ? How would perl know what you mean by
    print( 1,2,3 )[1];

    If knows the difference if you write   print +( 1,2,3 )[1];

Re: Getting single element from an array
by Anonymous Monk on Nov 01, 2012 at 09:19 UTC
    obj.method()[2] #when we know that method returns an array

    But you still have to wrap it with  System.out.println( ... ); , you don't get to omit () in java, in java () on calls are mandatory, but not in perl

Re: Getting single element from an array
by gurpreetsingh13 (Scribe) on Nov 01, 2012 at 09:36 UTC
    Got the point Sir. Thanks.
Re: Getting single element from an array
by itnomad (Scribe) on Nov 04, 2012 at 02:27 UTC

    This works:  print qw[adf ff f ][1];

Re: Getting single element from an array
by brx (Pilgrim) on Nov 05, 2012 at 17:31 UTC
    print ("adf","ff","f"); # Gladly prints the list print ("adf","ff","f")[1]; #Gives a syntax error

    Think to print() as a subroutine: you can write myfunc(...); but myfunc(...)[1]; is wrong.

    With a "gift package ( )", perl will be happy: myfunc( (...][1] );

    perl -e 'sub myfunc { return @_;}; my @res = myfunc(('a','b','c')[1]);print @res;' OK

    perl -e 'sub myfunc { return @_;}; my @res = myfunc('a','b','c')[1];print @res;' WRONG

    English is not my mother tongue.
    Les tongues de ma mère sont "made in France".