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

Rick Croote rick.croote at philips.com
Wed Jun 29 11:09:22 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

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 on.  I 
lost track of who posted this solution, you say J. Krahn, I say, very nice 
solution J. Krahn.  You gotta love elegant one line solutions :)

    my $string = "one";
    my ($first,$last) = (split /\s+/, $string)[0,-1];
    print "$first\n";
    print "$last\n";

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.pm.org/pipermail/spug-list/attachments/20050629/3f18f79d/attachment.html


More information about the spug-list mailing list