Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting code to perl sub, but not sure I'm doing it right
    primarykey
    data
    text
    <p>I'm working from a question I posted earlier (<a href="https://stackoverflow.com/questions/3032373/">here</a>), and trying to convert the answer to a sub so I can use it multiple times. Not sure that it's done right though. Can anyone provide a better or cleaner sub? </p> <p>I have a good deal of experience programming, but my primary language is PHP. It's frustrating to know how to execute in one language, but not be able to do it in another.</p> <pre><code>sub search_for_key { my ($args) = @_; foreach $row(@{$args-&gt;{search_ary}}){ print "@$row[0] : @$row[1]\n"; } my $thiskey = NULL; my @result = map { $args-&gt;{search_ary}[$_][0] } # Get the 0th column... grep { @$args-&gt;{search_in} =~ /$args-&gt;{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' =&gt; $ref_cam_make, 'search_in' =&gt; 'Canon EOS Rebel XSi' }); </code></pre> <p>---Edit---</p> <p>From the answers so far, I've cobbled together the function below. I'm <em>new</em> to Perl, so I don't really understand much of the syntax. All I know is that it throws an error (Not an ARRAY reference at line 26.) about that grep line.</p> <p>Since I seem to not have given enough info, I will also mention that:</p> <p>I am calling this function like this (which may or may not be correct):</p> <pre><code>search_for_key({ 'search_ary' =&gt; $ref_cam_make, 'search_in' =&gt; 'Canon EOS Rebel XSi' }); </code></pre> <p>And $ref_cam_make is an array I collect from a database table like this:</p> <pre><code>$ref_cam_make = $sth-&gt;fetchall_arrayref; </code></pre> <p>And it is in the structure like this (if I understood how to make the associative fetch work properly, I would like to use it like that instead of by numeric keys):</p> <pre><code>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-&gt;{search_ary}}){ print "@$row[0] : @$row[1]\n"; } print grep { $args-&gt;{search_in} =~ @$args-&gt;{search_ary}[$_][1] } @$args-&gt;{search_ary}; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload