I tried the following using an annonymous array and dereference to get a single expression.

Unfortunatly, since it requres TWO splits (one to generate the list of item in a line and one to figure out how many items are in that line), I don't think it is any more memory efficient.

In fact, I suspect it is LESS memory efficient since the annonymous arrays (mine uses two whereas the case the OP is trying to get rid o uses on a single array) take up memory.

But, as others pointed out, the OP wasn't clear on whether the issue was saving space or making the code takes less lines. So this appraoch ONLY saves lines...at the expense, IMHO, of readability and memory.

#!/usr/bin/perl use strict; use warnings; my @lines = ( "apple", "apple,banana,cherry", "banana,cherry", "apple,cherry", "banana", "cherry", ); foreach my $line (@lines){ my $item = (split(/\,/,$line))[int(rand(scalar(@{[split(/\,/,$line)]})))]; print "$item\n"; } exit(0);
ack Albuquerque, NM

In reply to Re: Pick random item from list of unknown length? by ack
in thread Pick random item from list of unknown length? by Cody Fendant

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.