开发者

Simplest way to match 2d array of keys/strings to search in perl?

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, r开发者_JAVA技巧ow[0][1]: Canon
row[2][0]: 25, row[2][1]: HP

Search String: Sony's Cyber-shot DSC-S600
End Result: 13


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜