in reply to slow CGI's

Hi AM,

Using a hash slice should do what you want.
Try this
#!/usr/bin/perl -w + use strict; + my @array = (1, 3, 5, 7, 9); my @numbers = (1, 4, 6 , 8); + my %nums; + # @nums{ @numbers } = 1; # incorrect @nums{ @numbers } = (1) x @numbers; # as jryan points out + print "FOUND\n" if $nums{ $array[0] };

Hope this helps

thinker

Update : corrected my error. thanks jryan

Replies are listed 'Best First'.
Re: Re: slow CGI's
by jryan (Vicar) on Jul 07, 2003 at 18:29 UTC

    I think you mean:

    @nums{ @numbers } = (1) x @numbers;

    With your example, you were assigning a 1-element list (the hash slice forces the rhs into list context) to the hash slice, and so only one item of the hash assigned to will have a true value. For instance:

    #!/usr/bin/perl -w use strict; use Data::Dumper; my @array = (1, 3, 5, 7, 9); my @numbers = (1, 4, 6 , 8); my(%nums, %rums); @nums{ @numbers } = 1; @rums{ @numbers } = (1) x @numbers; print Dumper \%nums; print Dumper \%rums;

    Yields the output:

    $VAR1 = { '8' => undef, '1' => 1, '4' => undef, '6' => undef }; $VAR1 = { '8' => 1, '1' => 1, '4' => 1, '6' => 1 };

    Which will, of course, lead to unexpected results if the item you are checking doesn't happen to be the one that the true value was assigned to.

    On the other hand, you could always change the last two lines of your example to this instead:

    @nums{ @numbers } = (); print "FOUND\n" if exists $nums{ $array[0] };

    It's more efficient, at any rate.