In the spirit of there's more then one way to do this, try this out:
Code:
use Fcntl ':flock';
# Usage: unsubscribe ('email@address.com');
sub unsubscribe {
my $email = shift;
# Read email file into $data.
open (DB, "< $email_db_path$email_db") or die "Can't read open: $!";
flock (DB, LOCK_SH);
read (DB, my $data, -s DB);
close DB;
# Check to see if the string $email followed by a pipe is in this file.
# and we see that we can remove the line.
if ((index ($data, "$email|") >= 0) and ($data =~ s/^$email.+\n//m)) {
open (DB, "> $email_db_path$email_db") or die "Can't write open: $!";
flock (DB, LOCK_EX);
print DB $data;
close DB;
print "Location: $redirect_unsub\n\n";
}
# If index returned -1, that means it didn't match.
else {
error ("Could not unsubscribe!");
return;
}
}
# Usage: subscribe ('email@address.com', 'name');
sub subscribe {
my ($email, $name) = @_;
# Read email file into $data.
open (DB, "< $email_db_path$email_db") or die "Can't read open: $!";
flock (DB, LOCK_SH);
read (DB, my $data, -s DB);
close DB;
# Check to see thtat the user already isn't subscribed.
if ((index ($data, "$email|") >= 0) and ($data =~ s/^$email\|.+\n//m)) {
error ("Already subscribed!");
return;
}
# Nope, add the user in.
open (DB, "> $email_db_path$email_db") or die "Can't write open: $!";
flock (DB, LOCK_EX);
print DB $data, "$email|$name\n";
close DB;
print "Location: $redirect_sub\n\n";
}
the
index function is a lot more efficent then a reg ex, and using
read is upto 9x faster in reading in a file then slurping it into an array.
If you have questions about this, feel free to ask!
Cheers,
Alex
--
Gossamer Threads Inc.