Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

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

by Aristotle (Chancellor)
on Jan 08, 2009 at 09:02 UTC ( #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.


Comment on Re: Is there an andand for Perl like there is in Ruby?
Select or Download Code
Re^2: Is there an andand for Perl like there is in Ruby?
by Leon Timmermans (Novice) 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
Node Status?
node history
Node Type: note [id://734845]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2014-09-22 22:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (205 votes), past polls