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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.