[geeks] Programming question.

alex j avriette avriettea at speakeasy.net
Tue Apr 2 09:09:50 CST 2002


>> In perl ...
>>
>> use Quantum::Superpositions;
>> @C = eigenstates(any(@B) != all(@A));

sick. sick. sick.

> Oh, sorry.  You wanted a SENSIBLE solution? :-)
>
> my @a = (1,3,5,7,9);
> my @b = (0,1,2,3,4,5,6,7,8,9);
> my @c = ();
>
> my %a = map { ($_, 1) } @a;
> foreach (@b) { push @c, $_ unless($a{$_}) }
>
> print join (', ', @c);

dave and i have talked about perl code and why he hates it and i dont. 
this is one instance where i wholeheartedly agree with dave. perl, like 
unix, is a collection of tools. a good perl programmer knows how and 
when to apply them. common examples:

"how do i get the length of a string?" (length)
"how do i chmod a file?" (chmod)
"how do i get items matching x pattern from y array?" (grep)

and so on.

my earlier example is most likely the best way to do this (barring some 
XS backend module which specializes in it -- list::util does not). the 
above solution may well work (i havent tested it), but youre using at 
least twice the memory, and moving a LOT slower. in fact, map is usually 
1-30% slower than foreach in every instance (and it has been said that 
using for instead of map is only for syntactic wussies who are afraid 
of $_).

when youre iterating over an array, use map, grep, and sort. thats what 
theyre there for. they have the unfortunate consequence of using more 
memory (ive consumed > 3gb before with a 15-layer map over 350,000 rows 
from a database, but thats extreme), but it is *tremendously* quicker 
because of the way it is handled in the back end (there are certain 
assumptions made for a map that arent made for a for).

i've got a little museum of map code: 
http://satan.posixnap.net/~alex/scorch/Documents/map_museum.pl.txt

anyhow, one more admonition about perl. *its not c!* program in perl 
when youre writing code in perl.

oh yeah. and print "@array" does what you want. look into the special $" 
variable.

alex


--
alex j avriette, perl hacker
avriettea at speakeasy.net
http://envy.posixnap.net/



More information about the geeks mailing list