On Jul 16, Powell, Ron said:

>while($db->FetchRow()){
>  %Data = $db->DataHash(First_Name,Last_Name);
>  foreach $key (sort(keys %Data)) {
>    print $key, '=', $Data{$key}, "\n";
>  }
>  print("\n");
>}
>
>Now, what appears to be happening is that only one row at a time is
>being processed and the other records are not being saved...  In
>essence, the %Data hash never contains more than two key/value pairs
>(First_Name = John, Last_Name = Smith for instance)...and the next
>FetchRow overwrites the current data...

Right -- this is because you're assigning to %Data, which in effect CLEARS
%Data and then fills in key-value pairs.  Just like:

  @array = (1..20);
  @array = (1..5);

ends up only storing (1,2,3,4,5) in @array.

>Should I load the contents of %Data into a different hash during each
>iteration of the while/fetchrow loop?  Frankly, from the little I know
>of working with hashes, I would have thought the first code snippet
>would have done it for me correctly...

Well, if you are certain the last names are unique, you can do this:

  my %people;

  while($db->FetchRow()){
    my %row = $db->DataHash(qw( First_Name Last_Name));
    $people{ $row{Last_Name} } = $row{First_Name};
  };

  # and then, to print sorted:

  for (sort keys %people) {
    print "$people{$_} $_\n";  # firstname lastname
  }

If there are NOT guaranteed unique last names, then a hash is not the data
structure for you.  You'll want to use an array.  In fact, an array is
probably the easiest way to go ANYWAY.

  my @people;

  while ($db->FetchRow) {
    my %row = $db->DataHash(qw( First_Name Last_Name ));
    push @people, [ @row{qw( First_Name Last_Name )} ];
  }

Now @people is an array of array references.  It looks like this:

  @people = (
    [ 'Jeff', 'Pinyan' ],
    [ 'Sam', 'Snead' ],
    [ 'Matt', 'Stone' ],
    [ 'Trey', 'Parker' ],
  );

But it's not sorted.  So we sort it:

  for (sort { $a->[1] cmp $b->[1] or $a->[0] cmp $b->[0] } @people) {
    print "@$_\n";  # firstname lastname
  }

The sort routine gets two elements of @people at a time, $a and $b.  These
are array references, and $a->[1] is the last name of one element, and
$a->[0] is the first name of the same element.  We compare last names, and
if they are the same, then we compare first names, so "Matt Smith" comes
before "Sally Smith".

The print "@$_\n" line just prints the array reference in $_ (which is the
elements of @people in sorted order).

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
** Look for "Regular Expressions in Perl" published by Manning, in 2002 **
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to