Gossamer Forum
Home : General : Perl Programming :

Shifting entries in a perl database

Quote Reply
Shifting entries in a perl database
Hello, I'm using DBMan for a database and it works great. I have a problem here that is not really related to DBMan though. I am modifying it for a different purpose. What I want to do is set up a system where each entry has two fields, a Name and a number. What I want to be able to do is best explained in an example. Here are the entries, listed by name and by number:
Joe, 1
Fred, 2
Bob, 3
Norm, 4
Louis, 5
Now, what I want to do is be able to take Norm (who is in 4) and move him to the second position, have fred move to the 3rd, bob to the fourth. This would have to keep going until it reached the number that Norm was previously located in. (in this case, 4). I do not want any two people to have the same number, so I want to end up with 1,2,3,4,5 as the numbers for people in the database.

This is maybe a bit confusing, but I can't think of how I could explain it better... Please tell me if and how it can be done!

Thanks,
Jason R.
Quote Reply
Re: Shifting entries in a perl database In reply to
Here's something you can play around with, should give you a start at least (may not be 100% correct):

open (DB, ">db.txt");
print DB qq~
Joe, 1
Fred, 2
Bob, 3
Norm, 4
Louis, 5
~;
close DB;

&myshift("Norm", 2);

sub myshift {
# --------------------------------------------------------
my ($user, $newpos) = @_;
my (%users, @index, $key, $pos);

open (DB, "<db.txt") or die "$!";
while (<DB&gt Wink {
(/^(.*),\s(\d+)$/) or next;
$users{$2} = $1; print "adding user $1 in pos $2\n";
($1 eq $user) and ($key = $2)
}
close DB;
$key or return undef; # Couldn't find the user.
@index = keys %users; print "User index on key($key): @index\n";

# Remove the user, -1 as we index from 0 in the array, not 1.
splice (@index, $key-1, 1); print "User removed: @index\n";

# Add him in the new position, -1 as we index from 0 in the array, not 1.
splice (@index, $newpos-1, 0, $key); print "User added: @index\n";

# Print it out.
foreach (@index) {
$pos++;
print "$users{$_}, $pos\n";
}
}
Quote Reply
Re: Shifting entries in a perl database In reply to
What is the code in the script that was turned into a wink?

open (DB, "<db.txt") or die "$!";
while (<DB> (right here) {
Quote Reply
Re: Shifting entries in a perl database In reply to
It was:

while ( <DB> ) {

the greater than followed by ) get's turned into a wink unfortunately (have to fix that)..

Basically it get's the next line of input from the database file and stores it in $_.

Alex