Ici, c’est la méthode qui est mise en valeur. Il y a d’autres moyens, plus efficaces, d’arriver au même résultat. Il faut surtout y voir la simplicité du script et la clarté du package. En gros tout les avantages de la construction Objet.
Si l’on appelle le programme de la manière suivante :
> ./doublon_ip.pl list.txt New ip found : 192.64.128.49 New ip found : 127.0.0.1 New ip found : 192.32.134.108 New ip found : 192.64.128.50 > ./doublon_ip.pl list.txt > ./doublon_ip.pl list.txt > ./doublon_ip.pl list2.txt New ip found : 212.28.45.68
Voici les deux fichiers de tests :
#!/usr/bin/perl -w use strict; use Doublon_Ip; my $dbip = Doublon_Ip->new(); while (<>) { my ($ip, $compagne) = split(/\s+/, $_, 2); unless ($dbip->check_status($ip)) { print "New ip found : $ip\n"; } $dbip->add_ip($ip); }
package Doublon_Ip; use strict; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $self = {}; $self->{IPLIST} = undef; $self->{FILE_STORE} = shift || "ip_doublon.txt"; bless($self); # but see below if (-r $self->{FILE_STORE}) { $self->load_db; } return $self; } sub DESTROY { my $self = shift; my $fh; open $fh, ">$self->{FILE_STORE}" or die; foreach my $k (keys %{$self->{IPLIST}}) { print $fh $k,"\n"; } close $fh; } sub load_db { my $self = shift; my $fh; open $fh, "$self->{FILE_STORE}" or die; map {chomp; $self->{IPLIST}->{$_} = 1; } <$fh>; close $fh; } sub add_ip($) { my $self = shift; my ($ip) = @_; if (defined $self->{IPLIST}->{$ip}) { $self->{IPLIST}->{$ip} += 1; } else { $self->{IPLIST}->{$ip} = 1; } } sub del_ip($) { my $self = shift; my ($ip) = @_; undef $self->{IPLIST}->{$ip}; } sub check_status($) { my $self = shift; my ($ip) = @_; defined $self->{IPLIST}->{$ip} ? $self->{IPLIST}->{$ip} : 0; } 1;