| 1 | package MYDan::Util::Hosts; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Carp; | ||
| 6 | |||
| 7 | use Tie::File; | ||
| 8 | use Fcntl 'O_RDONLY'; | ||
| 9 | |||
| 10 | use MYDan; | ||
| 11 | |||
| 12 | sub new | ||
| 13 | { | ||
| 14 | my ( $class, $path, %host ) = splice @_, 0, 2; | ||
| 15 | |||
| 16 | $path ||= "$MYDan::PATH/etc/hosts"; | ||
| 17 | |||
| 18 | if( -f $path ) | ||
| 19 | { | ||
| 20 | die "tie fail: $!" unless tie my @host, 'Tie::File', $path, mode => O_RDONLY, recsep => "\n"; | ||
| 21 | |||
| 22 | for my $host ( @host ) | ||
| 23 | { | ||
| 24 | next unless $host =~ /^\s*(\d+\.\d+\.\d+\.\d+)\s+([0-9a-zA-Z][\w\s\.\-]+)/; | ||
| 25 | map{$host{$_} = $1 }split /\s+/, $2; | ||
| 26 | } | ||
| 27 | } | ||
| 28 | |||
| 29 | bless \%host, ref $class || $class; | ||
| 30 | } | ||
| 31 | |||
| 32 | sub match | ||
| 33 | { | ||
| 34 | my $this = shift; | ||
| 35 | map{ $_ => $this->{$_} || $_ }@_; | ||
| 36 | } | ||
| 37 | |||
| 38 | sub hosts | ||
| 39 | { | ||
| 40 | my $this = shift; | ||
| 41 | return keys %$this; | ||
| 42 | } | ||
| 43 | |||
| 44 | sub dump | ||
| 45 | { | ||
| 46 | my $this = shift; | ||
| 47 | return %$this; | ||
| 48 | } | ||
| 49 | |||
| 50 | 1; | ||
| 51 | __END__ |