0

I'm looking for a one-liner that lets me grab the second return value from a subroutine.

Rather than this:

($a,$b)=function;
print $b

It should be possible to do something like this

print ??? function
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Steven Lu
  • 41,389
  • 58
  • 210
  • 364

2 Answers2

6

This works:

sub test { return (1,2) }
print ((test)[1]);  # Returns 2

This also works:

print +(func())[1], "\n";
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • 3
    `print((function)[1])` or `print +(function)[1]` to get the precedence right. See http://stackoverflow.com/questions/5055519/. – mob Feb 22 '11 at 04:12
  • ah, i was missing the parens. – Steven Lu Feb 22 '11 at 04:13
  • @Steven -- yea, me too when I was playing with it. Need the parens around the [], which seems strange to me. – jr. Feb 22 '11 at 04:16
  • @jr: that's because (some of) the parens aren't just for precedence like they usually are, they are part of the `(LIST)[LIST]` list slice operator, and then you need other parens or a leading + to let perl know the list slice parens aren't just parens enclosing print's parameters. – ysth Feb 22 '11 at 04:30
  • 1
    Also possible (less efficiently) with an array slice operator: `print [function()]->[1]`. Or `print pop @{[function()]}`. – ysth Feb 22 '11 at 04:31
0

assuming that function() returns a list, then using a slice like the poster above suggested works just fine. If it returns an array reference, then you need to access it appropriately, for instance (@{function()})[1] to dereference the aref and then slice it.

BadFileMagic
  • 701
  • 3
  • 7