views:

117

answers:

3

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.

A: 

Using POSIX (ereg_*) functions is deprecated as of PHP 5.3.0. If you use PCRE (preg_*) functions istead, they will work in perl as well. PCRE is an abbreviation for Perl Compatible Regular Expressions. If you need any help with rewriting the pattern for PCRE, post the original pattern.

cypher
+9  A: 

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.

Gordon
+2  A: 

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);
M42
thanks but what about the substr part? what is the value in $l in the case of php.
sfactor
`s/$pattern//` removes the pattern (if found), that do the substr in the same instruction.
M42
@M42 yah thanx for reminding me of that. could you tell me what the push function is doing. found is an array here but the values push are like a key and value structure in hash. so how would i print the end result from found? doing print "@found" doesn't seem to work.
sfactor
@sfactor: I've updated my answer.
M42