At 1:48 PM 10/17/00, Ronald J Kimball wrote: >On Tue, Oct 17, 2000 at 09:21:14AM -0700, Bruce Van Allen wrote: > >> Both return the item number, so subtract 1 to get the array index. Or >> modify the sub to subtract 1 and return a *reference* to the number. >> Returning a reference is necessary to avoid a false value if the >> value being searched for happens to appear in the first list item, >> which would have the index 0; if tested for truth 0 returns false, >> whereas a reference to it would return true. Then you have to >> dereference the number to use it as the array index. > >I still prefer returning '0 but true' to avoid this problem, the way some >of Perl's builtin functions do, rather than returning a reference. > Cool. The expression $list['0 but true'] works like $list[0] !! Using that allows the same return value to be used both for a truth test and also for an array index. Here are the refined subroutines, which determine whether a value appears as an item in a list, and if it does, provides the index of that item's position in the list. #!perl -w use strict; ## A list and some values to check for: my @list = qw/oil water grease fluid/; my @values = qw/water grease oil fluid waiter greas fluide oil water/; ## This loop checks each value in the list. ## Note the use of the index ($list[$item_num]). foreach my $value (@values) { if (my $item_num = inlist($value, @list)) { print "1 the array index of $list[$item_num] is $item_num.\n" } else { print "0 $value not found in the list.\n" } } ## This sub requires that the character '~' does not appear in the data: sub inlist { my $value = shift; local($_) = '~' . join('~', @_) . '~'; return unless /^(.*?~$value)~/; my $chunk = $1; $chunk =~ tr/~// - 1 || '0 but true' } ## This sub puffs up a hash; keys are the list items, values are their indices: sub inlist2 { my $value = shift; my %testhash; @testhash{@_} = ('0 but true', 1..@_); $testhash{$value} or return } __END__ The loop returns the following with either sub: 1 the array index of water is 1. 1 the array index of grease is 2. 1 the array index of oil is 0 but true. 1 the array index of fluid is 3. 0 waiter not found in the list. 0 greas not found in the list. 0 fluide not found in the list. 1 the array index of oil is 0 but true. 1 the array index of water is 1. 1; - Bruce __Bruce_Van_Allen___bva@cruzio.com__Santa_Cruz_CA__ # ===== Want to unsubscribe from this list? # ===== Send mail with body "unsubscribe" to macperl-request@macperl.org