On Mon, Oct 3, 2016 at 10:45 PM Lawrence Statton <[email protected]> wrote:
snip
> the =()= "operator" just does that without creating a temporary variable
snip
Almost, but not quite. You can see the difference when =()= is in list
context:
my @a = (my @temp) = get_clown_hat;
my @b = () = get_clown_hat;
@a will have the items returned by get_clown_hat and @b won't. The
assignment operators have a return value. For scalar assignment, it is
just the scalar being assigned, regardless of the context. For list
assignment in list context it is the list that was assigned:
$ perl -E '@a = ($a, $b) = 1 .. 100; say "a is ", join ", ", @a;'
a is 1, 2
$ perl -E '@a = () = 1 .. 100; say "a is ", join ", ", @a;'
a is
and the number of items on the right hand side of the assignment when it is
in scalar context:
$ perl -E '$a = () = 1 .. 100; say "a is $a"'
a is 100
$ perl -E '$a = ($b) = 1 .. 100; say "a is $a"'
a is 100
You can see how different approaches compare using the Benchmark module:
#!/usr/bin/perl
use strict;
use Benchmark;
use warnings;
my $max_hats = 100;
sub get_clown_hat {
return (0 .. $max_hats);
}
# here, scalar context is causing the .. operator
# to be the flip flop operator instead of the
# range operator, so we get 1E0 instead of
# 100 (the last item) or 101 (the count)
# when not compared to anything, the range operator
# compares against $. (the line number of the last
# line read from the currently selected file handle)
my $flip_flop_result = get_clown_hat;
print "wrong result: $flip_flop_result\n";
my %subs = (
array => sub {
my @a = get_clown_hat;
return scalar @a;
},
empty => sub {
my $count = () = get_clown_hat;
return $count;
},
);
for my $sub (keys %subs) {
print "$sub: ", $subs{$sub}(), "\n";
}
for my $n (1_000, 10_000, 100_000) {
$max_hats = $n;
print "\n$n items\n\n";
Benchmark::cmpthese -2, \%subs;
}
Avoiding copying the data is about twice as fast for counting items:
Use of uninitialized value $. in range (or flip) at bench.pl line 11.
wrong result: 1E0
array: 101
empty: 101
1000 items
Rate array empty
array 12620/s -- -52%
empty 26457/s 110% --
10000 items
Rate array empty
array 1310/s -- -50%
empty 2634/s 101% --
100000 items
Rate array empty
array 124/s -- -49%
empty 245/s 97% --