Loading ...
Sorry, an error occurred while loading the content.
 

Re: item number in an array

Expand Messages
  • b_harnish
    ... I believe you mean: # No commas needed @Color = qw(red green blue); # Not = , eq # = assigns # == compares numbers # eq compares alpha until ($input eq
    Message 1 of 3 , May 29 2:45 PM
      --- In perl-beginner@y..., "Chirhart, Brian" <bchirhart@f...> wrote:
      > Is there a better way to get the number of an item in an array other than:
      >
      > @Color = qw(red, green, blue)
      > until ($input = $Color[$x]) {
      > $x++;
      > }

      I believe you mean:
      # No commas needed
      @Color = qw(red green blue);
      # Not '=', 'eq'
      # = assigns
      # == compares numbers
      # eq compares alpha
      until ($input eq $Color[$x]) {
      $x++;
      }

      Try this:
      # This returns an array of matching index's
      # So, we put the first match in $x
      # $x == undef if no match found, otherwise, $x = index#
      my ($x) = grep { $input eq $Color[$_] } (0..$#Color);

      BTW:
      the above grep, essentially does this:
      for(0..$#Color) {
      push(@found, $_) if ($input eq $Color[$_]);
      }
      return @found;

      - Brian
    Your message has been successfully submitted and would be delivered to recipients shortly.