2

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 42, 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?

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • 1
    From a few days ago, see it [here](https://stackoverflow.com/a/75262096/4653379) (so this is a dupe really but nevermind) – zdim Feb 02 '23 at 19:39
  • Difficult to find the good (key) words to this special needs. – Gilles Quénot Feb 02 '23 at 20:13
  • 1
    Yes! It's an elusive topic. That comment of mine wasn't a complaint, just to inform :). – zdim Feb 02 '23 at 20:24
  • 1
    It's still a good question, and your answer provides good detail. I don't think harshly about "duplicates" -- much of the time they add good things to the discussion. (Sometimes they are indeed just pure dupes of course...) – zdim Feb 02 '23 at 20:31

2 Answers2

3

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

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

for another one.

mob
  • 117,087
  • 18
  • 149
  • 283
2

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

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223