SPUG: IndexOf in Perl?

aaron salo aaron at activox.com
Sun Jan 29 12:11:59 PST 2006


Tanwir Habib wrote:

>Many thanks for the reply.
>
>I'm not sure where I am wrong but its not working somehow
>
Hi Tanwir,
At the risk of being overly verbose, since you are new to perlish 
things, it may be useful to give you a solution that illustrates things 
in a less obscure manner than just calling a function in something from 
CPAN. And at the same time we get to use an array, a hash, and a regex. 
Instead of an obfuscated two liner, I wrote it out longways in the hope 
this may make it easier to see what's going on and perhaps make 
modifications to suit your need. Hooray.

The snippet below has a couple advantages, first, it uses regex match so 
it treats everything as strings (side benefit being you don't have to 
worry about whether to use 'eq' or '=='. It also corrects the potential 
flaw where there might be multiple matches in your list, if that should 
occur you get back a list of all of them instead of breaking on the 
first match. Welcome to perl and I hope you enjoy using it.

use strict;
my @array    = qw/AA AC AE AF AG CA CC CD DC CA FF RR 15 3M CA CB VV YY/;
my $matchval = 'CA';

# to get a list of the matches
# pass your matching string as the first item
# and your list after that
 
my %hits = listMatch($matchval, at array);

if (%hits) {
  
   foreach(sort {$a <=> $b} keys %hits) {
     
      # please note this is NOT the array index
      # it's the order in the list
      # subtract 1 to get the array index
     
      print qq(item $_ matches $hits{$_}\n);
   }
  
} else {
  
   print qq(sorry, no matches\n);
}

exit 0;

# ======

sub listMatch {

my @inbound = @_;
my $matchpattern = shift(@inbound);

my %outbound;
my $itemcount = @inbound;

   if ($itemcount) {
      for (my $i=1;$i<$itemcount;$i++) {
         my $thismember = $inbound[$i-1];
         if ($thismember =~ m/^$matchpattern$/) {
#            print qq(matching $thismember to $matchpattern as item $i\n);
            $outbound{$i} = $thismember;
         }
        
      }
     
   } else {
     
      # reserved for error handling, if no items received
  
   }

return(%outbound);

} # end sub listMatch


More information about the spug-list mailing list