Re: Interesting Use of Grep
by davorg (Chancellor) on Jun 28, 2001 at 19:02 UTC
|
If the list of values that you are matching against is
large then this method can get pretty inefficient. Remember
that grep always checks every element of the array.
In cases like that, it would be more efficient to do
something like this:
my $found = 0;
foreach (@long_list_of_values) {
if ($var eq $_) {
$found = 1;
last;
}
}
if ($found) {
# do something...
}
--
<http://www.dave.org.uk>
Perl Training in the UK <http://www.iterative-software.com> | [reply] [d/l] |
|
|
I favor the slightly more idiomatic look of
for (LIST) { last if $found = ($_ eq $wanted) }
japhy --
Perl and Regex Hacker | [reply] [d/l] |
|
|
for (LIST) { do{ something; last; } if ($_ eq $wanted) }
| [reply] [d/l] [select] |
|
|
|
|
|
|
|
Re (tilly) 1: Interesting Use of Grep
by tilly (Archbishop) on Jun 28, 2001 at 20:56 UTC
|
Note that the nested hash lookups are done for each iteration. It would be fastest to factor that out of the loop. If you can arrange it, turning the actual grep into a hash lookup is even faster, and I personally like the idiom:
if ($is_wanted{$my_variable_here}) {
# Do something
}
because I can turn the name of the hash into what is in effect an inline comment about how I am thinking. (Note that comments embedded within your code like this are more likely to be maintained than comments insert into code.)
In fact I like it enough to sometimes do that even when I know that building the hash is going to be slower. | [reply] [d/l] |
Re: Interesting Use of Grep
by Brovnik (Hermit) on Jun 29, 2001 at 18:36 UTC
|
use Quantum::Superpositions;
if ($x == any(qw(1 2 3 5 7 9 11)))
{
print "small Prime\n";
}
which IMHO is nice and readable.
-- Brovnik | [reply] [d/l] |
Re: Interesting Use of Grep
by John M. Dlugosz (Monsignor) on Jun 29, 2001 at 00:58 UTC
|
Instead of a small golf or something clever, or cluttering the routine with a few lines, I'd favor breaking it out into its own function:
if (in_list (@list, $my->{long}{to}{type}{variable}[0])
{
# do something...
}
That makes it clear what I mean there, rather than having a maintainer have to reverse-engineer the code. Then in that function anything goes, since it's purpose is clear and a maintainer could just replace the whole thing.
—John | [reply] [d/l] |
|
|
if( $variable in (LIST) )
{
#do something...
}
| [reply] [d/l] |
|
|
Really! There is a list module somewhere. But in general why limit it to == operation? A general select (map-like but not 1:1) would be good, and it can early-out in boolean context.
| [reply] |