develooper Front page | perl.perl5.porters | Postings from September 2012

Given vs for vs foreach (was Re: Auto-chomp)

Thread Next
David Golden
September 26, 2012 08:09
Given vs for vs foreach (was Re: Auto-chomp)
Message ID:
[I will continue my trend of creating new threads on new topics for
those tired of the old who might otherwise miss interesting tangents]

On Wed, Sep 26, 2012 at 10:12 AM, Aristotle Pagaltzis <> wrote:
> Granted, `given` is technically redundant, but it is nice to have to an
> alternative to `for ($singlescalar)` which is expressly dedicated to
> aliasing a topic. Using a single-iteration loop for its side effect of
> aliasing the topic always felt unnecessarily idiosyncratic and typically
> Perlish over-clever to me… I always feel sheepish having to explain the
> idiom to Perl novices.

I think it also made more sense when smartmatch allowed containers on the LHS.

    given ( @foo ) { ... } # like given ( \@foo )

Now that we don't, I don't know if given() should allow containers
anymore with implicit reference to the variable.

Overall, I find it sort of ugly that we have three things that are all
effectively the same:

    foreach ( $foo ) { ... }
    given ( $foo ) { ... }
    for ( $foo ) { ... }

The remaining benefit of given() is that it doesn't have any loop
setup overhead and it has a return value (though it needs to be
wrapped in do {...}):

    my $value = do { given ( $foo ) { ... } };

Is that really worth having another keyword?  Could for/foreach return
a value similarly (without overhead in void context)?  Could
for(SCALAR) be optimized to avoid the loop setup?  If we could do away
with given(), I'd prefer to see it removed.

when() feels more generally useful and I'm starting to question if we
need to keep given().  And I'm neutral to negative about smartmatch
now, so when() as an "if with implicit next" is the remaining thing
that interests me.


David Golden <>
Take back your inbox! →
Twitter/IRC: @xdg

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About