SPUG: spug: What is the idiomatic way to extractfirst/lastitemafter split?
Yitzchak Scott-Thoennes
sthoenna at efn.org
Thu Jun 30 10:49:41 PDT 2005
On Thu, Jun 30, 2005 at 09:28:06AM -0700, DeRykus, Charles E wrote:
> Ok, I characterized this as a "drain" because, superficially at
> least, you're filling a bigger bucket with a smaller one. The split
> output consists of a single item but the Action of the function
> split populates $first with that single item; and then backfills
> $last with an undef. Here's what I assume Rick was referring to in
> claiming that no "drain" occurred:
>
> perdoc -f split:
>
> When assigning to a list, if LIMIT is omitted, Perl supplies a LIMIT
> one larger than the number of variables in the list, to avoid
> unnecessary work.
>
>
> perl -MO=Deparse -e '($first,$last) = split(" ","foo");'
> ($first, $last) = split(" ", 'foo', 3);
>
>
> The split really generates only 1 element; behind the scenes, split
> orchestrates output so $first gets populated with that 1 element and
> then $last gets backfilled with an 'undef' because the original list
> is exhausted. Maybe that seat-of-the-pants explanation is flawed
> somehow...
>
> I assume Rick felt that because split generates values for both
> $first and $last this shouldn't be thought of as a "drain". To me,
> it just seems natural to call it a "drain" because there's really a
> 1 item output and that's trying to fill 2 slots.
But the case under consideration isn't ($first, $last) = split ...;,
it's ($first, $last) = ( split ... )[0, -1]; which indeed never leaves
$last undefined. If only one element is produced by split, both
$first and $last get assigned that value.
More information about the spug-list
mailing list