James Edward Gray II wrote:
On Feb 10, 2004, at 2:39 PM, Jan Eden wrote:
It has six characters which can be left out to minimize typing.Rob, I read the perlfaq paragraph you mentioned and found that it proposes a solution which does not make use of 'exists':
What's wrong with exists()? I like exists() and you're going to hurt it's feelings. :)
All of the solutions posted added more than six characters, so you'll need multiple tests before you start saving keystrokes. Make sure you're lazy in the good way. ;)
You could also use map() I guess, if you don't consider that a loop:For some irrational reason, I consider this more of a loop than your first/Rob's solution below.
@[EMAIL PROTECTED] = map { 1 } 0..$#blues;
map() is a loop, to be sure, but it comes from inside perl and thus should be faster much of the time than a loop you create yourself. (Compare 'foreach' and 'map_hash' in the results below.)
It's not for me to rewrite the docs (or perhaps it is?) butI finally came up with an idea of my own, just when I got up this morning:
for (@blues) { $is_blue{$_} = 1 }
does the same thing as
@[EMAIL PROTECTED] = (1) x @blues;
@[EMAIL PROTECTED] = 1 .. @blues;
This way each of the hash keys gets a value different from zero, so
if ($is_blue{$_})
still works.
Clever.
Now it might be hard to determine which of these two is faster.
Why would that be hard? ;)
#!/usr/bin/perl
use strict; use warnings;
use Benchmark;
my @blues = qw/azure cerulean teal turquoise lapis-lazuli/; my %is_blue;
timethese( 3000000, { foreach => '$is_blue{$_} = 1 foreach @blues', hash_slice => '@[EMAIL PROTECTED]', all_ones => '@[EMAIL PROTECTED] = (1) x @blues', map_ones => '@[EMAIL PROTECTED] = map { 1 } 0..$#blues', map_hash => '%is_bllue = map { $_ => 1 } @blues', range => '@[EMAIL PROTECTED] = 1 .. @blues' } );
__END__
And the results, from my G5:
Benchmark: timing 3000000 iterations of all_ones, foreach, hash_slice, map_hash, map_ones, range...
all_ones: 1 wallclock secs ( 1.76 usr + 0.00 sys = 1.76 CPU) @ 1704545.45/s (n=3000000)
foreach: 3 wallclock secs ( 2.39 usr + 0.00 sys = 2.39 CPU) @ 1255230.13/s (n=3000000)
hash_slice: 1 wallclock secs ( 0.94 usr + 0.00 sys = 0.94 CPU) @ 3191489.36/s (n=3000000)
map_hash: 2 wallclock secs ( 1.43 usr + 0.00 sys = 1.43 CPU) @ 2097902.10/s (n=3000000)
map_ones: 4 wallclock secs ( 3.91 usr + 0.00 sys = 3.91 CPU) @ 767263.43/s (n=3000000)
range: 1 wallclock secs ( 2.20 usr + 0.00 sys = 2.20 CPU) @ 1363636.36/s (n=3000000)
Looks like Rob is still the man to beat. :D
James
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>