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

最后都变了- 提交于 2019-12-01 01:38:49
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)

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