[San-Diego-pm] Perl Meeting on Monday, May 9th

Menolly menolly at mib.org
Tue May 10 11:40:00 PDT 2005


On Tue, 10 May 2005, Tkil wrote:

> Answer: Use the $statement_handle->{NAME_lc} property.  More details
> are in "perldoc DBI".  The only hiccup is that it returns an array
> ref; this means that you have to unpack it, and you should probably
> make a copy of it before you modify it.

And speaking of DBI and arrayrefs, here's the snippet of fun with map
and grep that I mentioned:
  my %taken;
  @taken{map $_->[0], @{$rd2->{'sth'}->fetchall_arrayref()}} = ();
  my @untaken = grep {!exists $taken{$_->[0]}} @{$rd->{'sth'}->fetchall_arrayref()};
  $testDigest = @untaken[rand(@untaken)]->[0];

$rd and $rd2 are hashrefs returned by a function in our internal DBI
wrapper.

I needed to select a random item from a pool, but it needed to be
one which has not already been used by this user.  The query in $rd2
selects items which have been used by this user; $rd is the pool.

First, I declare a hash, which will act as a lookup table.  I populate
it with the user's taken list using hash slicing, and dereferencing the
arrayrefs via map.  Next, I use grep to build a list of items in the
pool which have not been used.  Finally, I select a random arrayref from
the resulting list, deref, and use the data in the code that follows.

-- 
menolly at mib.org                    http://www.livejournal.com/~nolly/

On that day, many will say to me, "Lord, Lord, did we not prophesy in
your name, and cast out demons in your name, and do many mighty works
in your name?" And then will I declare to them, "I never knew you;
depart from me you evildoers." -- Matt 7:20-23, RSV


More information about the San-Diego-pm mailing list