SPUG: spug: What is the idiomatic way to extractfirst/lastitemafter split?
DeRykus, Charles E
charles.e.derykus at boeing.com
Wed Jun 29 11:41:25 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
>
>> Not true, the slice "[0,-1]" does not "drain", but just reuses the same element
>> in the case of one element after the split. This then creates the appropriate
>> 2 elements to initialize $first and $last. Of course, $string must be initialized
>> to something other than what it would split onmy $string = "one";
>> my ($first,$last) = (split /\s+/, $string)[0,-1];
>> print "$first\n";
>> print "$last\n";
True, but that's very much semantic overkill in my opinion. I'd have to argue that the result is
certainly the same as a "drain" even ,if technically, split is orchestrating the effect.
--
Charles DeRykus
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/spug-list/attachments/20050629/ab5d16b7/attachment.html
More information about the spug-list
mailing list