If you have the time, please take a look it. I'm updating some code for work, and I'd like all the core functions to be in a module. Before I get deeper into it, I'd like to know any pointers you'd be willing to offer. What's good to have in a module and what's not? How can I make OO modules and when should/shouldn't I use OO? Any insight or information you have is greatly appreciated.
#!/usr/bin/perl -w
package IPBlock;
use strict;
use Exporter;
use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
use constant BLOCKED_LIST => './data/ip_block.dat';
$VERSION = 1.00;
@ISA = qw(Exporter);
@EXPORT = qw(&checkIP);
@EXPORT_OK = qw(&checkIP &blockIP &unblockIP &returnIP);
%EXPORT_TAGS = (DEFAULT => \@EXPORT,
ALL => [qw(&checkIP &blockIP &unblockIP &returnIP)]);
sub checkIP {
# returns 1 if blocked
# returns 0 if not blocked
my $ip = shift;
open(my $fh, BLOCKED_LIST) or die("Cannot open r BLOCKED_LIST $!")
+;
flock($fh, 4);
my $returnvalue = 0;
while(<$fh>){
chomp;
if($_ =~ /\A$ip/){
$returnvalue = 1;
last;
}
}
close($fh);
return $returnvalue;
}
sub blockIP {
my $ip = shift;
open(my $fh, '+<', BLOCKED_LIST) or die("Cannot open r/w BLOCKED_L
+IST $!");
flock($fh, 2);
my @block = <$fh>;
chomp(@block);
my $returnvalue = 1;
if( grep(/\A$ip/, @block) ){
$returnvalue = 0;
}
if($returnvalue == 1){
push(@block, $ip);
seek($fh, 0, 0);
truncate($fh, 0);
print $fh "$_\n" foreach(@block);
}
close($fh);
return $returnvalue;
}
sub unblockIP {
my $ip = shift;
open(my $fh, '+<', BLOCKED_LIST) or die("Cannot open r/w BLOCKED_L
+IST $!");
flock($fh, 2);
my @block = <$fh>;
chomp(@block);
my $returnvalue = 0;
if( grep(/^$ip/, @block) ){
@block = grep(!/\A$ip/, @block);
$returnvalue = 1;
}
seek($fh, 0, 0);
truncate($fh, 0);
print $fh "$_\n" foreach(@block);
close($fh);
return $returnvalue;
}
sub returnIP{
open(my $fh, '+<', BLOCKED_LIST) or die("Cannot open r/w BLOCKED_L
+IST $!");
flock($fh, 4);
my @block = <$fh>;
close($fh);
chomp(@block);
return \@block;
}
1;