1 |
package WebPAC::Index; |
2 |
|
3 |
use warnings; |
4 |
use strict; |
5 |
|
6 |
use Carp; |
7 |
use Tie::Array::Sorted; |
8 |
use Log::Log4perl qw(get_logger :levels); |
9 |
use locale; |
10 |
|
11 |
=head1 NAME |
12 |
|
13 |
WebPAC::Index - create sorted index |
14 |
|
15 |
=head1 DESCRIPTION |
16 |
|
17 |
This module will create sorted index by headline (like thesaurus). |
18 |
|
19 |
=head1 METHODS |
20 |
|
21 |
=head2 new |
22 |
|
23 |
Create new sorted index object |
24 |
|
25 |
my $thes = new WebPAC::Index( |
26 |
log => 'log4perl.conf', |
27 |
); |
28 |
|
29 |
C<log> is optional parametar which specify filename of L<Log::Log4Perl> |
30 |
config file. Default is C<log.conf>. |
31 |
|
32 |
Default sort function is my C<headline>, non case sensitive. It can't be |
33 |
changed right now without editing of source. |
34 |
|
35 |
=cut |
36 |
|
37 |
sub new { |
38 |
my $class = shift; |
39 |
my $self = {@_}; |
40 |
bless($self, $class); |
41 |
|
42 |
my $log_file = $self->{'log'} || "log.conf"; |
43 |
Log::Log4perl->init($log_file); |
44 |
|
45 |
tie @{$self->{'index'}}, "Tie::Array::Sorted", sub { |
46 |
lc( $_[0]->{'headline'} ) cmp lc( $_[1]->{'headline'} ) |
47 |
}; |
48 |
|
49 |
return $self; |
50 |
} |
51 |
|
52 |
=head2 insert |
53 |
|
54 |
Insert data into index |
55 |
|
56 |
$index->insert( |
57 |
path => 'path', |
58 |
headline => 'headline text', |
59 |
); |
60 |
|
61 |
=cut |
62 |
|
63 |
sub insert { |
64 |
my $self = shift; |
65 |
|
66 |
my $data = {@_}; |
67 |
|
68 |
my $log = $self->_get_logger(); |
69 |
|
70 |
$log->logconfess("need path and headline!") unless (defined($data->{'path'}) && defined($data->{'headline'})); |
71 |
|
72 |
push @{$self->{'index'}}, $data; |
73 |
|
74 |
$log->debug("stored path: ",$data->{'path'}," headline: ",$data->{'headline'}); |
75 |
|
76 |
} |
77 |
|
78 |
=head2 elements |
79 |
|
80 |
Get all elements (sorted by locale) from sorted index. |
81 |
|
82 |
my @e = $index->elements; |
83 |
|
84 |
Each element is hash containing C<path> and C<headline>. |
85 |
|
86 |
print $e[0]->{'headline'}," is ",$e[0]->{'path'},"\n"; |
87 |
|
88 |
=cut |
89 |
|
90 |
sub elements { |
91 |
my $self = shift; |
92 |
|
93 |
my $log = $self->_get_logger(); |
94 |
|
95 |
$log->debug(scalar(@{$self->{'index'}})." elements in index"); |
96 |
|
97 |
return @{$self->{'index'}}; |
98 |
} |
99 |
|
100 |
# |
101 |
|
102 |
=head1 INTERNAL METHODS |
103 |
|
104 |
You shouldn't call this methods directly. |
105 |
|
106 |
=head2 _get_logger |
107 |
|
108 |
Get C<Log::Log4perl> object with a twist: domains are defined for each |
109 |
method |
110 |
|
111 |
my $log = $webpac->_get_logger(); |
112 |
|
113 |
=cut |
114 |
|
115 |
sub _get_logger { |
116 |
my $self = shift; |
117 |
|
118 |
my $name = (caller(1))[3] || caller; |
119 |
return get_logger($name); |
120 |
} |
121 |
|
122 |
1; |