CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Get hash reference from array where x = “abc”

 



PapaGeek
User

Mar 17, 2014, 5:32 AM

Post #1 of 4 (1463 views)
Get hash reference from array where x = “abc” Can't Post

I have an array of hash references built by this code snippet:


Code
	$sth = $dbh->prepare('SELECT * FROM Accounts'); 
$sth->execute;
while ( $hash_ref = $sth->fetchrow_hashref) {
my %dataHash;

$dataHash{"listID"} = ${$hash_ref}{FundListID};
$dataHash{"nickName"} = ${$hash_ref}{nickname};
push (@accountsHashArray, \%dataHash);
}

I can print out the array with this code:

Code
 	for (my $index = 0; $index < scalar (@accountsHashArray); $index++) 
{
my $hashRef = $accountsHashArray[$index];

my $listID = $$hashRef{"listID"};
my $nickName = $$hashRef{"nickName"};
my $w = $$hashRef{"w"};
my $h = $$hashRef{"h"};

say "$nickName uses list $listID";
}

Is there a proper perl syntax that would perform the following pseudo code line?

Code
 my $hashRef = $accountsHashArray[where nickName = “abc”];

Or, if the nickName’s are not unique,

Code
 my @hashRefArray = @accountsHashArray[where nickName = “abc”];



BillKSmith
Veteran

Mar 17, 2014, 6:00 AM

Post #2 of 4 (1461 views)
Re: [PapaGeek] Get hash reference from array where x = “abc” [In reply to] Can't Post


Code
my @hashRefArray = grep {$$_{nickName} eq 'abc'}@accountsHashArray

Good Luck,
Bill


PapaGeek
User

Mar 17, 2014, 6:15 AM

Post #3 of 4 (1459 views)
Re: [BillKSmith] Get hash reference from array where x = “abc” [In reply to] Can't Post

Thanks, your code is far more “Perlish” than the sub I wrote to do it, which is what I’m aiming for as I learn “Pearl”. LOL


FishMonger
Veteran / Moderator

Mar 17, 2014, 3:23 PM

Post #4 of 4 (1451 views)
Re: [PapaGeek] Get hash reference from array where x = “abc” [In reply to] Can't Post

Does your select statement return multiple rows for the same listID or nickName?

If not, then it would be cleaner and easier to use fetchall_hashref instead of fetchrow_hashref and manually building @accountsHashArray.
http://search.cpan.org/~timb/DBI-1.631/DBI.pm#fetchall_hashref

It would also be better to specify the 2 fields in the select statement instead of using * to select all fields.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives