Listing 2. Using DBIx::Recordset to copy user records from a source table (uregister)
to a target table (uregisternew).
use Angryman::User;
use DBIx::Recordset;
use Math::Random;
use strict;
use vars qw(%table %connect %profile);
$table{in} = 'uregister';
$table{out} = 'uregisternew';
%connect = (
'!DataSource' => 'DBI:mysql:test',
'!Username' => 'root'
);
# connect to database and SELECT * FROM uregister
*::uregister = DBIx::Recordset->Search ({
%connect,
'!Table' => $table{in}
});
# because we will re-use the target table many times, we separate the
# connection and insert steps with this recordset
*::uregisternew = DBIx::Recordset->Setup({
%connect,
'!Table' => $table{out}
});
# iterate through the recordsets from the old table:
while (my $record = $::uregister->Next) {
&randomize_user_profile;
# INSERT:
# the old table data into the new table along with
# the computed hash of profile data
$::uregisternew->Insert({%$record, %profile});
}
# Angryman::User::Profile is a hash in which each key is a reference
# to an array of profile choices. For example:
# $Angryman::User::Profile{gender} = [ 'male', 'female' ];
# $Angryman::User::Profile{age} = ['under 14', '14-19', '20-25', ... ];
# Because we don't have the actual data for the people in uregister,
# we randomly assign user profile data over a normal distribution.
# when copying it to uregisternew.
sub randomize_user_profile {
for (keys %Angryman::User::Profile) {
my @tmp = @{$Angryman::User::Profile{$_}};
$profile{$_} = random_uniform_integer(1, 0, $#tmp);
}
$profile{dob}='1969-05-11';
}