views:

47

answers:

1

Related to my previous question (found here), I want to be able to implement the answers given with a 2 dimensional array, instead of one dimensional.

Reference Array
row[1][0]: 13, row[1][1]: Sony
row[0][0]: 19, row[0][1]: Canon
row[2][0]: 25, row[2][1]: HP

Search String: Sony's Cyber-shot DSC-S600
End Result: 13
+2  A: 
use strict;
use warnings;

my @array = (
              [ 19, 'Canon' ],
              [ 13, 'Sony'  ],
              [ 25, 'HP'    ],
            );

my $searchString = "Sony's Cyber-shot DSC-S600";

my @result = map { $array[$_][0] }                        # Get the 0th column...
               grep { $searchString =~ /$array[$_][1]/ }  # ... of rows where the
                 0 .. $#array;                            #     first row matches

print "@result";  # prints '13'

The beauty of this approach is that it deals with the possibility of multiple matches, so if Sony and HP ever decided to collaborate on a camera, your code can return both! (13 25)

Zaid