<br><font size=2><tt><br>
> <br>
> <br>
> On 6/28/05, Bill Campbell <bill@celestial.com> wrote:<br>
> > On Tue, Jun 28, 2005, Uri London wrote:<br>
> > ><br>
> > ><br>
> > > What is the idiomatic way to extract first/last item
after split?<br>
> > ><br>
> > > More interestingly, why #2 doesn't work, while #3
does?<br>
> > <br>
> > If I want the first and last items from a split, I would probably
do <br>
> > it something like:<br>
> > <br>
> > my ($first, @rest) = split(...);<br>
> > my $last = pop(@rest);<br>
> ><br>
> <br>
> >> this might not work as one expects on a list of one, since
@rest <br>
> will be empty. ($last will contain undef <br>
> >>after the pop.) it's unclear from the original poster's <br>
> requirements what this edge case should return.<br>
> <br>
> True and the same thing applies to J. Krahn's elegant solution. Once
<br>
> the output's drained, the rest of the list will be undefined.<br>
> <br>
> ($first,$last) = (split ...)[0,-1]; # $last undefined
if list of 1<br>
> <br>
> --<br>
> Charles DeRykus<br>
</tt></font>
<br><font size=2><tt>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 :)</tt></font>
<br>
<br><font size=2><tt> my $string = "one";</tt></font>
<br><font size=2><tt> my ($first,$last) = (split /\s+/, $string)[0,-1];</tt></font>
<br><font size=2><tt> print "$first\n";</tt></font>
<br><font size=2><tt> print "$last\n";</tt></font>
<br>
<br>