SPUG: first vs //

Dave O cxreg at pobox.com
Wed Jul 18 16:38:53 PDT 2007


Actually, two things about this:

1) \() makes everything a reference and since sub{} returns a code
reference, it then passes a scalar reference to first and chokes, so it
would really need to be  ( \&foo, sub { $bar }, \&baz )

2) first does not return the result of the block (ala map), but $_ itself
(ala grep) so you'd either need to chain it to map, or dereference it
directly

      ($var) = map { $_->() } first { $_->() } ( \&foo, sub { $bar }, \&baz );
      $var = (first { $_->() } ( \&foo, sub { $bar }, \&baz ))->();


which probably is bad since you're running the sub twice now, or do
an assignment in the block

      $var = first { $_ = $_->() } ( \&foo, sub { $bar }, \&baz );

which looks odd, but is probably the closest you can get to

      $var = foo() // $bar // baz();

without //

//++ :)

	Dave

On Wed, 18 Jul 2007, Dave O wrote:

> And if one or more of your list elements are scalars
>
>      $var = first { $_->() } \( &foo, sub { $bar }, &baz );
>
> :)
>
> On Wed, 18 Jul 2007, Colin Meyer wrote:
>
> > On Wed, Jul 18, 2007 at 11:37:42AM -0700, Michael R. Wolf wrote:
> > > > Interestingly, Larry's 'first' suggestion is now available in the core:
> > > >
> > > >    use List::Util qw/first/;
> > > >
> > > >    $var  = first { defined } $foo, $bar, $baz;
> > >
> > > In the world of TMTOWTDI, I like.... *both*.
> > >
> > > I initially liked the use of 'first' as more intuitive (for my definition of
> > > intuitive).  In reading the "old arguments", I realized that the 'first'
> > > subroutine does not (in fact, cannot) do short circuiting, in which case the
> > > // operator is better.
> > >
> > > $var = $foo // $bar // $baz;
> > >
> > > Short circuiting (lazy evaluation) makes much more sense when functions are
> > > called since they could have a non-trivial cost and side-effects that may
> > > need to be avoided.  In some cases the later functions must be guarded
> > > against execution if earlier ones succeed.
> > >
> > > $var = foo() // bar() // baz();
> >
> > Short circuiting with first:
> >
> >     $var = first { $_->() } \( &foo, &bar, &baz );
> >
> > -Colin.
> > _____________________________________________________________
> > Seattle Perl Users Group Mailing List
> >      POST TO: spug-list at pm.org
> > SUBSCRIPTION: http://mail.pm.org/mailman/listinfo/spug-list
> >     MEETINGS: 3rd Tuesdays
> >     WEB PAGE: http://seattleperl.org/
> >
> >
> >
> _____________________________________________________________
> Seattle Perl Users Group Mailing List
>      POST TO: spug-list at pm.org
> SUBSCRIPTION: http://mail.pm.org/mailman/listinfo/spug-list
>     MEETINGS: 3rd Tuesdays
>     WEB PAGE: http://seattleperl.org/
>
>
>


More information about the spug-list mailing list