my $value = [ $x => $y ] -> [ $y <= $x ];
would not pass my code review.
I agree it’s confusing the first time and the => should be a skinny comma :P instead. That said, the Schwartzian transform is even more confusing the first time you see it. No one in a post 5.6 Perl world would suggest rewriting it with a bunch of temp arrays and for blocks. So, I advocate simple little idioms like the above when they offer something more than clever/pretty code.
So, thinking to possibly defend the clever/pretty one, I tried a Benchmark, which I'm not necessarily doing right so someone please jump in if it’s badly formed, and the one that might be the most semantically clear and I assumed would be the slowest is the fastest by a good measure. I forgot that List::Util is XS.
use strictures;
use Benchmark "cmpthese";
use List::Util "min"; # This is XS.
my @xy = ( [ 1, 0 ], [ 0, 1 ], [ 0, 0 ], [ 1, 1 ],
[ 1_000_000, 999_999 ], [ 999_999, 1_000_000 ] );
my $m; # Avoid void in comparisons.
cmpthese(10_000_000, {
list_util => sub { $m = min(@$_) for @xy },
ternary => sub {
$m = $_->[0] < $_->[1] ? $_->[0] : $_->[1] for
+@xy },
clever => sub {
$m = [ $_->[0], $_->[1] ]->[ $_->[0] <= $_->[1]
+ ] for @xy },
});
Rate clever ternary list_util
clever 347584/s -- -56% -68%
ternary 792393/s 128% -- -28%
list_util 1096491/s 215% 38% --
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.