From: Matt S Trout Date: Sun, 6 Jun 2010 00:43:53 +0000 (+0100) Subject: add & and | overloading to and and or X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=7e59992989cae0cab88fc76a246c427706b397c5;p=dbsrgits%2FData-Query.git add & and | overloading to and and or --- diff --git a/lib/Data/Query/ExprBuilder.pm b/lib/Data/Query/ExprBuilder.pm index 0a2f75e..9e12dd6 100644 --- a/lib/Data/Query/ExprBuilder.pm +++ b/lib/Data/Query/ExprBuilder.pm @@ -5,13 +5,14 @@ use Data::Query::Constants qw(DQ_OPERATOR DQ_VALUE); use Scalar::Util (); use overload ( + # binary operators (map { - my $op = $_; - $op => sub { + my ($overload, $as) = ref($_) ? @$_ : ($_, $_); + $overload => sub { Data::Query::ExprBuilder->new({ expr => { type => DQ_OPERATOR, - operator => { perl => $op }, + operator => { perl => $as }, args => [ map { (Scalar::Util::blessed($_) @@ -27,11 +28,17 @@ use overload ( }, }); } - } qw(+ - * / % ** << >> . < > == != lt le gt ge eq ne)), + } + qw(+ - * / % ** << >> . < > == != lt le gt ge eq ne), + + # since 'and' and 'or' aren't operators we borrow the bitwise ops + [ '&' => 'and' ], [ '|' => 'or' ], + ), + # unsupported (map { my $op = $_; $op => sub { die "Can't use operator $op on a ".ref($_[0]) } - } qw(<=> cmp x) + } qw(<=> cmp x ^ ~) ), ); diff --git a/t/expr.t b/t/expr.t index cc33fe6..590cc80 100644 --- a/t/expr.t +++ b/t/expr.t @@ -86,3 +86,25 @@ expr_is { 3 == $_->foo } throws_ok { expr { $_->foo <=> 3 } } qr/\QCan't use operator <=>/, 'Exception on bad operator'; + +expr_is { $_->foo & $_->bar } + { + type => DQ_OPERATOR, + operator => { perl => 'and' }, + args => [ + expr { $_->foo }, + expr { $_->bar }, + ], + }, + 'Masquerade for & as and ok'; + +expr_is { $_->foo | $_->bar } + { + type => DQ_OPERATOR, + operator => { perl => 'or' }, + args => [ + expr { $_->foo }, + expr { $_->bar }, + ], + }, + 'Masquerade for | as or ok';