Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Is there an andand for Perl like there is in Ruby?

by Aristotle (Chancellor)
on Jan 08, 2009 at 09:02 UTC ( [id://734845]=note: print w/replies, xml ) Need Help??


in reply to Is there an andand for Perl like there is in Ruby?

You can almost do this in Perl, but it requires sticking a method in UNIVERSAL (awful) and loading autobox::Core (because by default not everything is an object), both of which highly intrusive changes.

use autobox::Core; use Class::Null; sub UNIVERSAL::andand { return defined $_ ? $_ : Class::Null->new for +shift }

However, even with autobox loaded you cannot call methods on undef. So for all the intrusion you accepted for this it will still fail. You just have to be explicit:

for ( grep $_, $shop->ShopperDueDate ) { say $_->day_name() }

You can try to abstract this out a little, but then you get either a different kind of verbosity:

sub iftrue { for ( grep $_, $_[0] ) { $_[1]->() } } iftrue $shop->ShopperDueDate, sub { say $_->day_name() };

Or if you try to fix that it reads in the wrong order:

sub cond(&$) { for ( grep $_, $_[1] ) { $_[0]->() } } cond { say $_->day_name() } $shop->ShopperDueDate;

And don’t even think of “fixing” this with Filter::Simple. If source filters are the answer then you’re asking the wrong question. You will have mysterious bugs if you go down that route because source filters always break. How badly depends on filter in question; yours is a case where the type of breakage is bad.

What might (eventually) be possible is to implement something like this with Devel::Declare voodoo, which is (becoming) a macro system and therefore not prone to the problems of source filters.

Makeshifts last the longest.

Replies are listed 'Best First'.
Re^2: Is there an andand for Perl like there is in Ruby?
by Leon Timmermans (Acolyte) on Jan 08, 2009 at 16:12 UTC
    I've just written Scalar::Andand, using a similar approach. It handles undefined cases, though that may be buggy in a lot of cases. Check your local CPAN mirror soon.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://734845]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (4)
As of 2024-04-16 17:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found