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

Yitzchak Scott-Thoennes sthoenna at efn.org
Thu Jun 30 01:09:06 PDT 2005


(somewhat reformatted for better readability and attribution)

On Wed, Jun 29, 2005 at 11:41:25AM -0700, DeRykus, Charles E wrote:
> Rick Croote wrote:
> > DeRykus, Charles E wrote:
> > > 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 on.
> >     my $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.

Can you expand on that?  Using a list slice on [0,-1] is an idiom
to get the first and last elements; sometimes it looks like this:

   my ($min, $max) = (sort { $a <=> $b } @values)[0, -1];

While there is an argument for writing completely or almost completely
idiom free perl, I don't see how using an idiom like this could be
described as "semantic overkill".  And split's role is just creating
the list; I don't understand what you mean by orchestrating.

It sounds to me like you have an interesting point to make, but I'm
completely failing to understand you; I'd appreciate it if you could
make another attempt.


More information about the spug-list mailing list