For example:
return reduce(sub { $a * $b; }, 1, (1..$n));
would be: reduce { $a * $b } 1..$n;
This my $output = 1;
for my $i (1..$n) {
$output *= $i;
}
would be: $output *= $_ for (1..$n)
So, I have a question for you(assuming you write perl for a living). Is this your preferred style, or you do this to appease readability police which demands programming languages be readable by non programmers? Because really, what kind of programmer programs in perl and is averse to $_? $output *= $_ for (1..$n)
and you're right to call me on it. If I am writing a multi-line for loop, I do like to name the loop var though.I think this is an interesting point (in a discussion about readability), do non-perl coders think the one-liner (with 'for' suffix) is more or less readable?
(I also prefer explicit return for maintenance reasons, except possibly in one-line subs)
It does since 5.005 - so for a good long time now :-)
The reduce version (again, I'm unsure of const mem req). Comes in at ~1.4s:
This would allocate the array I'm afraid. You'd could use something liek List::Gen's reduce() to get around that.
def function(x, y, z):
versus
sub function { my ($x, $y, $x) = @_; }
The overhead is only really the 'my = @_;' chars, but it is annoying. On the other hand, it does allow you to do things like partially unpack args and pass the rest as a bundle to a super class.
def method(self, *args):
a, b = args[:2]
super(self).method(*args[:2])
Perl's lack of using the definition for the variables doesn't necessarily make it 'more powerful.'And with @_, you're free to use positional arguments, named arguments, variable arity, etc. without penalty. Some languages only give you some of that.
use Method::Signatures::Simple;
http://search.cpan.org/~rhesa/Method-Signatures-Simple-1.02/...But you might instead want to look at this (or similar with Moose support) to get simple type declarations:
http://search.cpan.org/~barefoot/Method-Signatures-20120523/...
First one (not 100% sure it's constant memory, I think perl optimises the for to avoid instantiating the (1..$n) list:
(Took the value up to 5000 to get something which ran long enough to get a measurement, on my laptop it runs (including startup time) in ~1.2s. (Can we compare runtime too? I know we're discussing readability, but I'm interested).The reduce version (again, I'm unsure of const mem req). Comes in at ~1.4s:
The add a constant (true lambda, closing over lexicals in scope, etc etc) is 'sub': (doesn't have the python lambda limitations). (Be aware that perl GC is refcounted though, so ref cycles are possible).Edit: I think the languages are comparable in terms of features and also readability. People may dislike leading sigils and that's fair, but I dislike python's "no need to declare your vars, just hope you don't typo an assignment" approach to lexicals.