I have an array of hashes that contains information about access points (name, mac address, etc.). I need to add serial numbers to this list, and I have to query the controller based on the AP's MAC address since this is a 1:1 relationship (i.e. there should never be MAC duplicates, and each MAC address has a specific corresponding serial number). Once I parse the response from the controller, I pick out the serial number. Now I need to update the AP hash and make sure the serial number gets paired with the element containing the correct MAC address. How can I do this? My only thought is to search the array each time finding the one that matches (using indices) and then use that current index value to update the hash. As an example:

#!c:/perl/bin/perl use strict; use warnings; my @aps; my $new_hash = {}; #Here I pull in a text file and parse it line by line, which I'm #omitting, but it's a while loop that populates the #hash and pushes to the array $new_hash->{'ap_name'} = "AP One"; $new_hash->{'ap_MAC'} = "00:00:00:00:00:00"; $new_hash->{'ap_model'} = "1131"; push (@aps, $new_hash);

So let's say we use the MAC address of all zeros to query the controller for the serial number. Now I have to find the one and only element in my AoH that has that MAC address and add its serial number. My current thinking is to do this:

for my $i (0 .. $#aps) { if $aps[$i]->{'ap_MAC'} eq "00:00:00:00:00:00" { $aps[$i]->{'serial'} = "FTX12345678"; } }

Rather than do an inefficient search that could potentially search the entire array (if it's the last element that matches) is there a more efficient way of directly accessing this matching element?

Regards,
Scott

In reply to Add Hash Key Based on Matching Another Key by spickles

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.