use Modern::Perl; sub givelist { my @rtn = ('a', 'b', 'c'); return @rtn; } #say givelist()[1]; my @list = givelist(); say $list[1];
I have a sub that returns a list. Frequently (but not always), I want just one element of the list. I have a variable containing the index of the element I want. When I first wrote the code, I wrote it as I wrote line 8, now commented out, in the SSCCE above. This fails at compile time:
X:\Data\Perl>perl ListTest.pl syntax error at ListTest.pl line 8, near ")[" Execution of ListTest.pl aborted due to compilation errors.
Splice didn't help, either. Changing the line to say splice(givelist(), 1, 1); resulted in a warning as well as an error:
X:\Data\Perl>perl ListTest.pl splice on reference is experimental at ListTest.pl line 8. Not an ARRAY reference at ListTest.pl line 8.
It's no big deal to write two lines and use an array for this single purpose, but it feels wrong. I expected Perl's DWIMmishness to be able to handle line 8 as I originally wrote it. Is there a way to get the single element I sometimes want without the business of an additional array?
Regards,
John Davies
Update: The suggested action works perfectly. Many thanks to all. Now I'll try to understand the ideas behind it!
In reply to [Solved] Pick a single item from a sub's return list by davies
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |