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

寵の児 提交于 2019-12-03 22:49:53

问题


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

回答1:


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)



来源:https://stackoverflow.com/questions/3032373/simplest-way-to-match-2d-array-of-keys-strings-to-search-in-perl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!