How do I get the first item from a function that returns an array in Perl?
perl
Solution
my $item = (function_returning_list())[0];
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 say
my ($item) = function_returning_list();
This puts `function_returning_list` in list context and does assignment (in order) to the variables in the left-hand-side list.
It is important to note that
sub function_returning_list {
return ("a", "b", "c")
}
my $item = function_returning_list();
will likely not do what you expect. The `$item` variable 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 `for` loops.
Problem
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?