Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a simple browser user-agent parser in Perl?

I needed to make a simple browser user agent parser in Perl. I have found a PHP code that does this but my knowledge is rather limited (esp. in regular expressions). So, here is the code whose Perl equivalent I want to write.

if ($l = ereg($pattern, $agent, $a = array()))
        {
          array_push($found, array("product" => $a[1], "version" => $a[3], "comment" => $a[6]));
          $agent = substr($agent, $l);
        }

The $agent is the user-agent string passed as argument, and returns an array of associative arrays $found, each one defining a product/comment in the agent string (key of the associative array are product, version, comment). The $pattern is the user-agent regular expression I am searching which I already know.

So, how would this look like in Perl?

Edit: Seems like there is an confusion about whether I want a Perl compatible regex or an equivalent function in Perl. I am looking for an Perl function and syntax that does the same thing.

like image 733
sfactor Avatar asked Dec 29 '22 06:12

sfactor


2 Answers

You can use the CPAN module HTTP::BrowserDetect to sniff out various information about the browser and the device it runs on, including but by far not limited to version, engine and vendor.

like image 166
Gordon Avatar answered May 09 '23 13:05

Gordon


Your PHP script could be written in Perl like :

my @found;
if ($agent =~ s/$pattern//) {
  push @found, {product => $1, version => $3, comment => $6};
}

In order to print the content of array @found :

use Data::Dumper;
print Dumper(\@found);
like image 24
Toto Avatar answered May 09 '23 13:05

Toto