Introducing PL/Perl

There is a lot more to say about PL/pgSQL. However, not everything can be covered in one book, it is time to move on to the next procedural language. PL/Perl has been adopted by many people as the ideal language to do string crunching. As you might know, Perl is famous for its string manipulation capabilities and is therefore still fairly popular after all these years.

To enable PL/Perl, you have two choices:

test=# create extension plperl; 
CREATE EXTENSION 

test=# create extension plperlu; CREATE EXTENSION

You can deploy trusted or untrusted Perl. If you want both, you have to enable both languages.

To show you how PL/Perl works, I have implemented a function that simply parses an email address and returns true or false. Here is how it works:

test=# CREATE OR REPLACE FUNCTION verify_email(text)  
RETURNS boolean AS 
$$ 
if   ($_[0] =~ /^[a-z0-9.]+@[a-z0-9.-]+$/) 
{ 
  return true; 
} 
return false; 
$$ LANGUAGE 'plperl'; CREATE FUNCTION 

A text parameter is passed to the function. Inside the function, all those input parameters can be accessed using $_. In this example, the regular expression is executed and the function is returned.

The function can be called just like any other procedure written in any other language:

test=# SELECT verify_email('[email protected]'); 
 verify_email
-------------- t (1 row) test=# SELECT verify_email('totally wrong');
verify_email
-------------- f (1 row)

Keep in mind that you cannot load packages and so on if you are inside a trusted function. For example, if you want to use the w command to find words, Perl will internally load utf8.pm, which, of course, is not allowed.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset