Home > Mobile >  How to print nth element of Perl expression returning a list?
How to print nth element of Perl expression returning a list?

Time:02-03

I try to get the first element of

$object->method()

that is returning a list.

My first though was to try:

$object->method()[0]

But I get this error:

syntax error at script.pl line 8, near ")["
Execution of script.pl aborted due to compilation errors.

so I tried:

print ($object->method())[0];

but Perl 'eat' the ( ) to use with print, and still have the error.

what I need is to do:

print((object->method())[0]);

Is there a simpler way to do this?

CodePudding user response:

There's a special trick to do this:

print  ($object->method())[0]

from perldoc perlfunc:

Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use parentheses, the simple but occasionally surprising rule is this: It looks like a function, therefore it is a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. Whitespace between the function and left parenthesis doesn't count, so sometimes you need to be careful:

    print 1 2 4;      # Prints 7.
    print(1 2)   4;   # Prints 3.
    print (1 2) 4;    # Also prints 3!
    print  (1 2) 4;   # Prints 7.
    print ((1 2) 4);  # Prints 7.

From #perl@libera IRC:

explanations

CodePudding user response:

It's Perl, so there are many special tricks to do this.

print [$object->method()]->[0]

for another one.

  • Related