Just reread your comment about "In real code". If you have an array instead of the 1..10, the ternary operator is the way to go. print for @a ? @a : 1..11 will have the first @a in scalar context (hence checking if there are any elements in the array) and the second @a in list context, returning the elements of the array. The 1..11 will properly have list context and generate the list (1,2,...,11).

Array slices are different. They don't have a scalar context per se; if scalar context is imposed (i.e. by being the first operand to ?:) the last element of the slice will be returned (and checked for truth by ?:). So assuming your desired-but-not-working-as-is-code was print for @a[@indices] or 1..11 you need to decide what you mean to do by checking @a[@indices] for truth. That could be any of a number of things. Perhaps one of these would be what you meant:

print for grep($a[$_], @indices) ? @a[@indices] : 1..11; print for grep(defined $a[$_], @indices) ? @a[@indices] : 1..11; print for grep(exists $a[$_], @indices) ? @a[@indices] : 1..11; print for !grep(!$a[$_], @indices) ? @a[@indices] : 1..11; print for !grep(!defined $a[$_], @indices) ? @a[@indices] : 1..11; print for !grep(!exists $a[$_], @indices) ? @a[@indices] : 1..11; # update: actually use slices after ?
I.e. use the array if (any/all) of the elements are (true/defined/existing), otherwise fall back on 1..11.

In reply to Re: for loops and 'and' by ysth
in thread for loops and 'and' by Anonymous Monk

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.