<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML ><HEAD ><TITLE >PL/Perl Functions and Arguments</TITLE ><META NAME="GENERATOR" CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK REV="MADE" HREF="mailto:pgsql-docs@postgresql.org"><LINK REL="HOME" TITLE="PostgreSQL 8.4.12 Documentation" HREF="index.html"><LINK REL="UP" TITLE="PL/Perl - Perl Procedural Language" HREF="plperl.html"><LINK REL="PREVIOUS" TITLE="PL/Perl - Perl Procedural Language" HREF="plperl.html"><LINK REL="NEXT" TITLE="Database Access from PL/Perl" HREF="plperl-database.html"><LINK REL="STYLESHEET" TYPE="text/css" HREF="stylesheet.css"><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=ISO-8859-1"><META NAME="creation" CONTENT="2012-05-31T23:30:11"></HEAD ><BODY CLASS="SECT1" ><DIV CLASS="NAVHEADER" ><TABLE SUMMARY="Header navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TH COLSPAN="5" ALIGN="center" VALIGN="bottom" >PostgreSQL 8.4.12 Documentation</TH ></TR ><TR ><TD WIDTH="10%" ALIGN="left" VALIGN="top" ><A HREF="plperl.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="10%" ALIGN="left" VALIGN="top" ><A HREF="plperl.html" >Fast Backward</A ></TD ><TD WIDTH="60%" ALIGN="center" VALIGN="bottom" >Chapter 40. PL/Perl - Perl Procedural Language</TD ><TD WIDTH="10%" ALIGN="right" VALIGN="top" ><A HREF="plperl.html" >Fast Forward</A ></TD ><TD WIDTH="10%" ALIGN="right" VALIGN="top" ><A HREF="plperl-database.html" ACCESSKEY="N" >Next</A ></TD ></TR ></TABLE ><HR ALIGN="LEFT" WIDTH="100%"></DIV ><DIV CLASS="SECT1" ><H1 CLASS="SECT1" ><A NAME="PLPERL-FUNCS" >40.1. PL/Perl Functions and Arguments</A ></H1 ><P > To create a function in the PL/Perl language, use the standard <A HREF="sql-createfunction.html" ><I >CREATE FUNCTION</I ></A > syntax: </P><PRE CLASS="PROGRAMLISTING" >CREATE FUNCTION <TT CLASS="REPLACEABLE" ><I >funcname</I ></TT > (<TT CLASS="REPLACEABLE" ><I >argument-types</I ></TT >) RETURNS <TT CLASS="REPLACEABLE" ><I >return-type</I ></TT > AS $$ # PL/Perl function body $$ LANGUAGE plperl;</PRE ><P> The body of the function is ordinary Perl code. In fact, the PL/Perl glue code wraps it inside a Perl subroutine. A PL/Perl function must always return a scalar value. You can return more complex structures (arrays, records, and sets) by returning a reference, as discussed below. Never return a list. </P ><DIV CLASS="NOTE" ><BLOCKQUOTE CLASS="NOTE" ><P ><B >Note: </B > The use of named nested subroutines is dangerous in Perl, especially if they refer to lexical variables in the enclosing scope. Because a PL/Perl function is wrapped in a subroutine, any named subroutine you create will be nested. In general, it is far safer to create anonymous subroutines which you call via a coderef. See the <TT CLASS="LITERAL" >perldiag</TT > man page for more details. </P ></BLOCKQUOTE ></DIV ><P > The syntax of the <TT CLASS="COMMAND" >CREATE FUNCTION</TT > command requires the function body to be written as a string constant. It is usually most convenient to use dollar quoting (see <A HREF="sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING" >Section 4.1.2.4</A >) for the string constant. If you choose to use escape string syntax <TT CLASS="LITERAL" >E''</TT >, you must double any single quote marks (<TT CLASS="LITERAL" >'</TT >) and backslashes (<TT CLASS="LITERAL" >\</TT >) used in the body of the function (see <A HREF="sql-syntax-lexical.html#SQL-SYNTAX-STRINGS" >Section 4.1.2.1</A >). </P ><P > Arguments and results are handled as in any other Perl subroutine: arguments are passed in <TT CLASS="VARNAME" >@_</TT >, and a result value is returned with <TT CLASS="LITERAL" >return</TT > or as the last expression evaluated in the function. </P ><P > For example, a function returning the greater of two integer values could be defined as: </P><PRE CLASS="PROGRAMLISTING" >CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$ if ($_[0] > $_[1]) { return $_[0]; } return $_[1]; $$ LANGUAGE plperl;</PRE ><P> </P ><P > If an SQL null value<A NAME="AEN49425" ></A > is passed to a function, the argument value will appear as <SPAN CLASS="QUOTE" >"undefined"</SPAN > in Perl. The above function definition will not behave very nicely with null inputs (in fact, it will act as though they are zeroes). We could add <TT CLASS="LITERAL" >STRICT</TT > to the function definition to make <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN > do something more reasonable: if a null value is passed, the function will not be called at all, but will just return a null result automatically. Alternatively, we could check for undefined inputs in the function body. For example, suppose that we wanted <CODE CLASS="FUNCTION" >perl_max</CODE > with one null and one nonnull argument to return the nonnull argument, rather than a null value: </P><PRE CLASS="PROGRAMLISTING" >CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$ my ($x,$y) = @_; if (! defined $x) { if (! defined $y) { return undef; } return $y; } if (! defined $y) { return $x; } if ($x > $y) { return $x; } return $y; $$ LANGUAGE plperl;</PRE ><P> As shown above, to return an SQL null value from a PL/Perl function, return an undefined value. This can be done whether the function is strict or not. </P ><P > Anything in a function argument that is not a reference is a string, which is in the standard <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN > external text representation for the relevant data type. In the case of ordinary numeric or text types, Perl will just do the right thing and the programmer will normally not have to worry about it. However, in other cases the argument will need to be converted into a form that is more usable in Perl. For example, here is how to convert an argument of type <TT CLASS="TYPE" >bytea</TT > into unescaped binary data: </P><PRE CLASS="PROGRAMLISTING" > my $arg = shift; $arg =~ s!\\(?:\\|(\d{3}))!$1 ? chr(oct($1)) : "\\"!ge;</PRE ><P> </P ><P > Similarly, values passed back to <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN > must be in the external text representation format. For example, here is how to escape binary data for a return value of type <TT CLASS="TYPE" >bytea</TT >: </P><PRE CLASS="PROGRAMLISTING" > $retval =~ s!(\\|[^ -~])!sprintf("\\%03o",ord($1))!ge; return $retval;</PRE ><P> </P ><P > Perl can return <SPAN CLASS="PRODUCTNAME" >PostgreSQL</SPAN > arrays as references to Perl arrays. Here is an example: </P><PRE CLASS="PROGRAMLISTING" >CREATE OR REPLACE function returns_array() RETURNS text[][] AS $$ return [['a"b','c,d'],['e\\f','g']]; $$ LANGUAGE plperl; select returns_array();</PRE ><P> </P ><P > Composite-type arguments are passed to the function as references to hashes. The keys of the hash are the attribute names of the composite type. Here is an example: </P><PRE CLASS="PROGRAMLISTING" >CREATE TABLE employee ( name text, basesalary integer, bonus integer ); CREATE FUNCTION empcomp(employee) RETURNS integer AS $$ my ($emp) = @_; return $emp->{basesalary} + $emp->{bonus}; $$ LANGUAGE plperl; SELECT name, empcomp(employee.*) FROM employee;</PRE ><P> </P ><P > A PL/Perl function can return a composite-type result using the same approach: return a reference to a hash that has the required attributes. For example: </P><PRE CLASS="PROGRAMLISTING" >CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text); CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$ return {f2 => 'hello', f1 => 1, f3 => 'world'}; $$ LANGUAGE plperl; SELECT * FROM perl_row();</PRE ><P> Any columns in the declared result data type that are not present in the hash will be returned as null values. </P ><P > PL/Perl functions can also return sets of either scalar or composite types. Usually you'll want to return rows one at a time, both to speed up startup time and to keep from queueing up the entire result set in memory. You can do this with <CODE CLASS="FUNCTION" >return_next</CODE > as illustrated below. Note that after the last <CODE CLASS="FUNCTION" >return_next</CODE >, you must put either <TT CLASS="LITERAL" >return</TT > or (better) <TT CLASS="LITERAL" >return undef</TT >. </P><PRE CLASS="PROGRAMLISTING" >CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$ foreach (0..$_[0]) { return_next($_); } return undef; $$ LANGUAGE plperl; SELECT * FROM perl_set_int(5); CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$ return_next({ f1 => 1, f2 => 'Hello', f3 => 'World' }); return_next({ f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' }); return_next({ f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' }); return undef; $$ LANGUAGE plperl;</PRE ><P> For small result sets, you can return a reference to an array that contains either scalars, references to arrays, or references to hashes for simple types, array types, and composite types, respectively. Here are some simple examples of returning the entire result set as an array reference: </P><PRE CLASS="PROGRAMLISTING" >CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$ return [0..$_[0]]; $$ LANGUAGE plperl; SELECT * FROM perl_set_int(5); CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$ return [ { f1 => 1, f2 => 'Hello', f3 => 'World' }, { f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' }, { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' } ]; $$ LANGUAGE plperl; SELECT * FROM perl_set();</PRE ><P> </P ><P > If you wish to use the <TT CLASS="LITERAL" >strict</TT > pragma with your code, the easiest way to do so is to <TT CLASS="COMMAND" >SET</TT > <TT CLASS="LITERAL" >plperl.use_strict</TT > to true. This parameter affects subsequent compilations of <SPAN CLASS="APPLICATION" >PL/Perl</SPAN > functions, but not functions already compiled in the current session. To set the parameter before <SPAN CLASS="APPLICATION" >PL/Perl</SPAN > has been loaded, it is necessary to have added <SPAN CLASS="QUOTE" >"<TT CLASS="LITERAL" >plperl</TT >"</SPAN > to the <A HREF="runtime-config-custom.html#GUC-CUSTOM-VARIABLE-CLASSES" >custom_variable_classes</A > list in <TT CLASS="FILENAME" >postgresql.conf</TT >. </P ><P > Another way to use the <TT CLASS="LITERAL" >strict</TT > pragma is to put: </P><PRE CLASS="PROGRAMLISTING" >use strict;</PRE ><P> in the function body. </P ></DIV ><DIV CLASS="NAVFOOTER" ><HR ALIGN="LEFT" WIDTH="100%"><TABLE SUMMARY="Footer navigation table" WIDTH="100%" BORDER="0" CELLPADDING="0" CELLSPACING="0" ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" ><A HREF="plperl.html" ACCESSKEY="P" >Prev</A ></TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="index.html" ACCESSKEY="H" >Home</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" ><A HREF="plperl-database.html" ACCESSKEY="N" >Next</A ></TD ></TR ><TR ><TD WIDTH="33%" ALIGN="left" VALIGN="top" >PL/Perl - Perl Procedural Language</TD ><TD WIDTH="34%" ALIGN="center" VALIGN="top" ><A HREF="plperl.html" ACCESSKEY="U" >Up</A ></TD ><TD WIDTH="33%" ALIGN="right" VALIGN="top" >Database Access from PL/Perl</TD ></TR ></TABLE ></DIV ></BODY ></HTML >