SPUG: spug: What is the idiomatic way to extract first/lastitem after split?

DeRykus, Charles E charles.e.derykus at boeing.com
Wed Jun 29 10:37:35 PDT 2005

On 6/28/05, Bill Campbell <bill at celestial.com> wrote:
> On Tue, Jun 28, 2005, Uri London wrote:
> >
> >
> >   What is the idiomatic way to extract first/last item after split?
> >
> >   More interestingly, why #2 doesn't work, while #3 does?
> If I want the first and last items from a split, I would probably do 
> it something like:
>        my ($first, @rest) = split(...);
>        my $last = pop(@rest);
>> this might not work as one expects on a list of one, since @rest will be empty. ($last will contain undef 
>>after the pop.) it's unclear from the original poster's requirements what this edge case should return.

True and the same thing applies to J. Krahn's elegant solution. Once 
the output's drained, the rest of the list will be undefined.

($first,$last) = (split ...)[0,-1];    # $last undefined if list of 1

Charles DeRykus

More information about the spug-list mailing list