An empty list, in list context, is just that -- a list with 0 elements. In scalar context, though, something must be assigned, and
undef is that assigned value. Indexing beyond the end of a list, in list context, returns an empty list, and
undef in scalar context.
It is a possible oddity, though, that indexing an element of a list which is
undef and assigning it to a list returns an empty list, and not the
undef that was there -- this is probably because it was within the same blanket solution to the problem above. However, in 5.6.0, this buggish behavior was removed.
# in 5.005_02
$x = (1,2,3)[10]; # $x is undef
@x = (1,2,3)[10]; # @x is (), not (undef)
@x = (undef)[0]; # @x is (), not (undef)
# in 5.6.0
$x = (1,2,3)[10]; # $x is undef
@x = (1,2,3)[10]; # @x is (), not (undef)
@x = (undef)[0]; # @x is (undef), not ()
My golf approach would be:
# returns the collapsed list: 15 chars
# 123456789_12345
sub collapse {grep{defined}@_}
# returns the collapsed list, via array ref: 20 chars
# 123456789_123456789_
sub collapse {grep{defined}@{+pop}}
# modifies array ref elements in place: 26 chars
# 123456789_123456789_123456
sub collapse {@$_=grep{defined}@{$_=pop}}
japhy --
Perl and Regex Hacker
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.