> Hi all, > > Does anyone know if there is a perl module that gets the prefered languages > of the browser in their preference order? > > I know to get them from $ENV{HTTP_ACCEPT_LANGUAGE} environment variable, but > I don't know how to parse correctly that string. > I have tried reading the RFC which talks about this, but I don't understand > it very well.
It *IS* confusing, isn't it? Reading through http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 Give me the following code snippet my $language_accept = 'da,en-gb;q=0.8,en;q=0.7'; my @range = split(',', $language_accept); @range now has the values ( 'da', 'en-gb;q=0.8', 'en;q=0.7' ); So, a language and an optional preference value. Now, we can use a couple of regexps (smarter people can do this in one regexp ....) to extricate the salient data for my $range (@range) { my ($language, $preference); unless (($language, $preference) = $range =~ /(.*);q=([\d\.]*)/) { $language = $range; $preference = 1.0; } Now, we have a loop iterating across all of the possible language-preference pairs and normalizing.... Let's build an array of hashrefs to hold the language-prerence pairs: push @preference, { language => $language, preference => $preference } ; While *MY* web browser appears to sort language preference automatically in descending order of preference, the specification is silent about the issue -- just for safety's sake, let's explicitly sort: @preference = sort { $b->{preference} <=> $a->{preference} } @preference; All together, that looks like: ------------------------------ begin perl code ------------------------------ #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $language_accept = 'da,en-gb;q=0.8,en;q=0.7,x-pig-latin;q=0.001,es-mx;q=0.3'; my @range = split(',', $language_accept); my @preference; for my $range (@range) { my ($language, $preference); unless (($language, $preference) = $range =~ /(.*);q=([\d.]*)/) { $language = $range; $preference = 1.0; } push @preference, { language => $language, preference => $preference } ; } @preference = sort { $b->{preference} <=> $a->{preference} } @preference; foreach my $preference (@preference) { print $preference->{language},"\n"; } ------------------------------- end perl code ------------------------------- Plugging this into a CGI and doing something useful with it is, as they say, left as an exercise to the reader. -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Lawrence Statton - [EMAIL PROTECTED] s/aba/c/g Computer software consists of only two components: ones and zeros, in roughly equal proportions. All that is required is to sort them into the correct order. -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>