@w = (1, 2, 3, 4, 5) ;
grep { $w->{$_} ++ } @w ;
print "found\n" if exists $w->{3} ;
On Wed, 2007-08-15 at 12:16 +0300, Amir E. Aharoni wrote:
> It's a very simple question, consider it a sanity check:
>
> How can i check that a value is present in a list?
>
> In Perl 6 there's a lovely thing called quantum:
>
> my $set = any(1, 2, 3, 4, 5);
> if (3 == $set) {
> say "found";
> }
>
> It is not found in Perl 5.8. There's a CPAN module called
> Quantum::Superpositions that emulates this. Maybe it will be present
> in Perl 5.10.
>
> Now, what is the simplest way to do it in Perl 5.8 without CPAN modules?
>
> Isn't there anything better than this:
>
> my @set = (1, 2, 3, 4, 5);
> foreach (@set) {
> if (3 == $_) {
> print "found\n";
> last;
> }
> }
>
> Or is there some builtin or standard library function that i am missing?
>
> grep may be clever, but it iterates over the whole list, and i don't need it.
>
> The Perl Cookbook suggests using a hash if i just need to test for the
> presence of an element in a list. I can create a hash with just keys
> and empty values:
>
> my %set = (
> 'a' => '',
> 'b' => '',
> 'c' => '',
> );
> if (exists $set{'a'}) {
> print "found\n";
> }
>
> However, using a hash without values is a bit counterintuitive. Or
> maybe i can write it in a more readable way?..
>
> Also, can there be significant performance or memory optimizations if
> i use a hash instead of a loop on large sets? (I am talking about many
> megabytes of data.)
>
_______________________________________________
Perl mailing list
[email protected]
http://perl.org.il/mailman/listinfo/perl