Nathan Wiger wrote:
> Tom Christiansen wrote:
> >
> > Ever consider then having
> >
> >     ($a, $b, $c) = <FH>;
> > or
> >     @a[4,1,5] = <FH>;
> >
> > only read three lines?  I mean, how many if any builtins would it
> > make sense to make aware of this, and do something "different"?
>
> Personally, I think this would be really cool; stuff like this is what I
> was trying to poke at. Lots more power and flexibility. I could name
> lots of builtins this potentially makes sense for:
>
>    ($one, $two) = grep /pat/, @data;
>    ($k1, $k2)   = keys %hash;  # leave index at $k3?
>    @a[6,5,4]    = map { split ' ' } @line;
>    ($last)      = reverse @array;
>
> And then there's splice, sort, and any and every user-defined sub too.
> The only problem is when grep and map are used to change values on the
> fly...this will have to be addressed. But actually, the behavior could
> potentially be quite cool - maybe only the number requested back are
> changed. Hmmm.
>
The problem with making these builtins respect the number of return values
context in want() is that, as Nate mentions, the expressions may have
side-effects that are desired for the whole list.

An alternative approach is to make these builtins respect lazy(), as defined
by RFC 123:

<quote>
What if adding laziness to a list context was up to the programmer
and passed through functions that can support it:

        for (lazy(grep {$h{$_}->STATE eq 'NY'} keys %h)){
                $h{$_}->send_advertisement();
        };


would cause a lazy list is passed to C<for>, and increment of
the object's "letters_sent_total" field might break the iteration.


        for (grep {$h{$_}->STATE eq 'NY'} lazy(keys %h)){
                $h{$_}->send_advertisement();
        };


causes a lazy list to be passed to our filter function C<grep>, saving
us from allocating the entire C<keys> array.  C<Grep> is still in
the default busy context, so it returns a busy array, which C<for>
can iterate over safely.
</quote>

By returning a lazy list, elements that are never used are never calculated.

That way the programmer could decide whether or not they want the Perl 5
list-gobbling behaviour, or lazy behaviour, as they require.


Reply via email to