1 package Lirama::Loc2::Auto;
13 $self->[1]{optimize} = $_[0] if @_;
14 return $self->[1]{optimize};
18 my ($class, $path, @langpref) = @_;
20 my $langs = @langpref>0; # languages specified
21 langpref(@langpref) if $langs; # set default language preference
23 my $node = [ # array for faster access to common [0]
27 optimize => $langs, # assume langpref won't change if specified
30 return bless $node, $class;
34 my ($self, $file) = @_;
36 unless (exists $self->[0]{$file}) {
37 my $filename = $self->[1]{path}.'/'.$file; # perl file returning l10n hash
38 my $extlang = '.'.langpref(); # file tag for the preferred language
39 my $ext = ".pl"; # extension for $filename
41 $filename .= $extlang # get language-optimized file
42 if $self->[1]{optimize} and -r $filename.$extlang.$ext;
44 tie %{$self->[0]{$file}}, "Lirama::Loc2", do $filename.$ext;
45 } # initialize Loc for this file
47 return $self->[0]{$file}
50 # Basically same as Tie::StdHash
52 sub EXISTS { exists $_[0]->[0]{$_[1]} }
53 sub FIRSTKEY { my $a = scalar keys %{$_[0]->[0]}; each %{$_[0]->[0]} }
54 sub NEXTKEY { each %{$_[0]->[0]} }
63 Lirama::Loc::Auto - Localize strings, initialize automatically
67 use Lirama::Loc::Auto;
69 tie my %L, "Lirama::Loc::Auto", "path/to/translation/files", "en";
71 print $L{numbers}{7}; # "seven"
75 Setup a hash containing multiple L<Lirama::Loc|Lirama::Loc> objects, which
76 open automatically on demand.
80 =item C<tie %tie, "Lirama::Loc::Auto", $path, @languages>
82 Will setup a hash to automatically load data files from P<$path/*.pl>.
83 These files should only return an anonimous translation hash.
85 If @languages is set, it will be taken as the default language preference.
88 =item C<$tie{$file}{$string}>
90 The first time a translation is accessed from C<$tie{$file}{$string}>, it will
91 create a Lirama::Loc object from P<$path/$file.pl>.
103 We'll create P<./includes/loc/index.pl> with the following contents:
112 en => sub { "%d user".($_[0]!=1 && "s")." have visited this site." },
116 Setup a hash with user defined language preferences, and a fallback to English.
118 my @langpref = split(',', $ENV{HTTP_ACCEPT_LANGUAGE});
119 tie my %loc, "Lirama::Loc::Auto", "includes/loc", @langpref, "en";
121 And display the I<welcome> string:
123 print $loc{index}{welcome};
125 If the user wanted Dutch texts, it will show I<welkom>. In case the user wanted
126 French for example, it will fallback to English.
128 print $loc{index}{["%d visits", ++$counter]};
132 L<Lirama::Loc|Lirama::Loc>
136 Mischa POSLAWSKY <shiar@shiar.org>
138 Copyright 2005 Mischa POSLAWSKY. All rights reserved.