LPM: record creation in perl

Frank Price fprice at upended.org
Tue Feb 6 07:45:21 CST 2001


On Mon, Feb 05, 2001 at 09:41:46PM -0500, Kenneth Rogers wrote:

> I've been trying to puzzle this one out of the cookbook for about
> half an hour now and I just can't quite get it.
> 
> p.383 if you want to follow along.

I don't have it in front of me now, but I'll try :-)

> They've created a record '$record' which is an anonymous hash, they
> claim to be able to make a hash of these records for use
> 
> "#store record $byname{ $record->{NAME} } = $record; "

So this looks like %byname is a hash, the keys of which are a string
describing the NAME of the record (hopefully unique), and the values
of which are the anon hash itself.  This is functionally the same as
doing this:

  my @records;
  foreach my $thing (@bunch_of_things) {
      my $record = { ATTR=>'val', ... };  # could combine these two
      push (@records, $record);
  }

except that with the %byname hash you can look it up by name, of
course.

> So then in order to make a bunch of these does this mean I need to
> have a $record that's separate for each one that I want to build?
> I'm hoping not I'm trying to make a dynamic system where I can
> create these records (the one's I'm using have 4 integers and an
> array that contains integers and characters right now).  The problem
> I see right now is that I don't know how to just add a new record to
> '$byname' without completely creating the whole record first, 

AFAIK, whether it's a anonymous hash or blessed object, you'll need to
create one for each "thing" you want to work with.  But you can use a
my variable inside a loop to create the hash and then store it in
another hash or array.  Since it is stored in the hash or array, it
continues to exist when the my variable goes out of scope.

> I'd
> rather be able to say something like
> 
> $byname{$record->{NUMBER} } = { NUMBER => 2, PARENT => 1, BOARD =>
> @board };
> 
> but I can't tell if that's legal ( it doesn't compile but that could
> be my fault and not that its impossible to do. )

I think the problem here is that $record->{NUMBER} doesn't refer to
anything, at least from what I can see.  If you want to key off
NUMBER, maybe:
   $byname{'2'} = {NUMBER => 2, PARENT => 1, BOARD => > @board };

is better.  Actually in this case, you might use an array to hold
them:

   $array[2] = {NUMBER => 2, PARENT => 1, BOARD => > @board };

and then you can do foreach my $record (sort @array) and use them.

Hope this helps,

-Frank.
-- 
Frank Price | fprice at upended.org | www.upended.org/fprice/
GPG key: www.upended.org/fprice/gpg.asc | E Pluribus Unix




More information about the Lexington-pm mailing list