最简单的方法来匹配键/字符串的二维数组在Perl中搜索? [英] Simplest way to match 2d array of keys/strings to search in perl?

查看:135
本文介绍了最简单的方法来匹配键/字符串的二维数组在Perl中搜索?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与我以前的问题(在这里找到)相关,我希望能够实现与2维数组一起给出的答案,而不是一维。

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


推荐答案

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'

这种方法的优点在于它处理多重匹配的可能性,所以如果索尼和惠普决定在相机上合作,你的代码可以同时返回! ( 13 25

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)

这篇关于最简单的方法来匹配键/字符串的二维数组在Perl中搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆