davies has asked for the wisdom of the Perl Monks concerning the following question:
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Pick a single item from a sub's return list
by BrowserUk (Patriarch) on Oct 31, 2015 at 11:25 UTC | |
by roho (Bishop) on Oct 31, 2015 at 12:41 UTC | |
by BrowserUk (Patriarch) on Oct 31, 2015 at 13:01 UTC | |
|
Re: Pick a single item from a sub's return list
by shmem (Chancellor) on Oct 31, 2015 at 11:28 UTC | |
|
Re: [Solved] Pick a single item from a sub's return list
by Not_a_Number (Prior) on Oct 31, 2015 at 12:16 UTC | |
by mr_ron (Deacon) on Oct 31, 2015 at 13:53 UTC |