You
could answer the problem by using
grep or the way you specified in your question, but if you are considering using it in the same
manner that it works in SQL you need a
hash for performance reasons:
#!/usr/bin/perl -w
use strict;
use Benchmark qw(:all);
my @choices = qw|a b c|;
my %choices = map{$_=>1}@choices;
my @cData = <DATA>;
timethese(100000,{'Damn Slow'=>\&parseData1,
'Much Better'=>\&parseData2});
sub parseData1 {
foreach (@cData){
chomp;
my @items = split/,/,$_;
#slow way,
foreach my $item (@items){
if(grep {$item eq $_} @choices){
#print qq|FOUND $item|;
}
}
}
}
sub parseData2 {
foreach(@cData){
chomp;
foreach my $item (split/,/,$_){
if ($choices{$item}){
#print qq|FOUND $item\n|;
}
}
}
}
__DATA__
z,t,m,u,a,b,c
s,t,l,m,z,a,s
c,b,a,m,u,t,n
k,l,t,s,z,r,t
Produces:
Benchmark: timing 100000 iterations of Damn Slow, Much Better...
Damn Slow: 9 wallclock secs ( 8.81 usr + 0.00 sys = 8.81 CPU) @ 11
+348.16/s
n=100000)
Much Better: 4 wallclock secs ( 3.88 usr + 0.00 sys = 3.88 CPU) @ 2
+5806.45/s
(n=100000)
Celebrate Intellectual Diversity
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.