A simple PL/Perl function

Now, let's write our first simple Perl function to make sure that PL/Perl is installed correctly. We will use a sample function from the Perl FAQs, at http://perldoc.perl.org/perlfaq5.html#How-can-I-output-my-numbers-with-commas-added%3f, to write a PL/Perl function that adds commas to a number:

CREATE OR REPLACE FUNCTION commafy (integer) RETURNS text 
AS $$
  local $_  = shift;
  1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
  return $_;
$$ LANGUAGE plperl;

This function uses a smartly written regex to add commas to your numbers. Let's try and run it:

testdb=# SELECT commafy(1000000);
 commafy  
-----------
 1,000,000
(1 row)

The code works and the function looks similar to other functions we have been writing in PL/pgSQL and PL/Python. The ...

Get PostgreSQL Server Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.