I have a function that returns an array, and I’d like to get just the first item from that array without ever declaring a variable for the array. Basically, it should be something like:
functionReturningArray()[1]
Except that doesn’t work.
I really don’t want to waste space declaring the whole array since I don’t need it, and I’d rather not waste an extra line of code. Anyway to do this in one line?
Functions cannot return arrays, they can return the contents of an array (i.e. a list). Lists are indexed starting at
0, so the first item of a function’s return is(func)[0]. You could also sayThis puts
function_returning_listin list context and does assignment (in order) to the variables in the left-hand-side list.It is important to note that
will likely not do what you expect. The
$itemvariable will be assigned"c". This is because there is no such thing as a list in scalar context. Instead, you have the comma operator in scalar context, and that evaluates the lefthand expression in void context, discards the result, then evaluates the righthand side in scalar context.I call a sequence (rather than a list) and is useful if a few situations like C-style
forloops.