将代码转换为perl sub,但不确定我做得对

Ben*_*nee 2 perl function

我正在处理我之前发布的一个问题(这里),并尝试将答案转换为子,以便我可以多次使用它.不确定它是否正确完成.任何人都可以提供更好或更清洁的子?

我有很多编程经验,但我的主要语言是PHP.知道如何用一种语言执行,但却无法在另一种语言中执行,这令人沮丧.

sub search_for_key
{
    my ($args) = @_;

    foreach $row(@{$args->{search_ary}}){
        print "@$row[0] : @$row[1]\n";
    }

    my $thiskey = NULL;

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

    print "\nReturning: " . $thiskey . "\n";
    return $thiskey;    
}

search_for_key({
    'search_ary' => $ref_cam_make, 
    'search_in' => 'Canon EOS Rebel XSi'
});
Run Code Online (Sandbox Code Playgroud)

- -编辑 - -

从目前为止的答案,我拼凑了下面的功能.我是Perl的新手,所以我对语法的理解并不多.我所知道的是它会抛出一个关于grep线的错误(不是第26行的ARRAY引用).

由于我似乎没有给出足够的信息,我还要提到:

我这样调用这个函数(可能是也可能不正确):

search_for_key({
    'search_ary' => $ref_cam_make, 
    'search_in' => 'Canon EOS Rebel XSi'
});
Run Code Online (Sandbox Code Playgroud)

$ ref_cam_make是我从数据库表中收集的数组,如下所示:

$ref_cam_make = $sth->fetchall_arrayref;
Run Code Online (Sandbox Code Playgroud)

它就是这样的结构(如果我理解了如何使关联提取正常工作,我想用它来代替数字键):

Reference Array
Associative
row[1][cam_make_id]: 13, row[1][name]: Sony

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

sub search_for_key
{
    my ($args) = @_;

    foreach my $row(@{$args->{search_ary}}){
        print "@$row[0] : @$row[1]\n";
    }

    print grep { $args->{search_in} =~ @$args->{search_ary}[$_][1] } @$args->{search_ary};
}
Run Code Online (Sandbox Code Playgroud)

FMc*_*FMc 5

您正朝着2D数组的方向移动,其中[0]元素是某种ID号,[1]元素是相机制作.虽然这种方法快速而肮脏,但很快就会导致代码难以理解.如果您使用更丰富,更具说明性的数据结构,您的项目将更易于维护和发展.

以下示例使用哈希引用来表示相机品牌.更好的方法是使用对象.当你准备好迈出这一步时,请看看穆斯.

use strict;
use warnings;

demo_search_feature();

sub demo_search_feature {
    my @camera_brands = (
        { make => 'Canon', id => 19 },
        { make => 'Sony',  id => 13 },
        { make => 'HP',    id => 25 },
    );

    my @test_searches = (
        "Sony's Cyber-shot DSC-S600",
        "Canon cameras",
        "Sony HPX-32",
    );

    for my $ts (@test_searches){
        print $ts, "\n";
        my @hits = find_hits($ts, \@camera_brands);
        print '  => ', cb_stringify($_), "\n" for @hits;
    }
}

sub cb_stringify {
    my $cb = shift;
    return sprintf 'id=%d make=%s', $cb->{id}, $cb->{make};
}

sub find_hits {
    my ($search, $camera_brands) = @_;
    return grep { $search =~ $_->{make} } @$camera_brands;
}
Run Code Online (Sandbox Code Playgroud)