1 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>43.1. PL/Perl Functions and Arguments</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" /><link rel="prev" href="plperl.html" title="Chapter 43. PL/Perl — Perl Procedural Language" /><link rel="next" href="plperl-data.html" title="43.2. Data Values in PL/Perl" /></head><body id="docContent" class="container-fluid col-10"><div class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">43.1. PL/Perl Functions and Arguments</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="plperl.html" title="Chapter 43. PL/Perl — Perl Procedural Language">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="plperl.html" title="Chapter 43. PL/Perl — Perl Procedural Language">Up</a></td><th width="60%" align="center">Chapter 43. PL/Perl — Perl Procedural Language</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="plperl-data.html" title="43.2. Data Values in PL/Perl">Next</a></td></tr></table><hr /></div><div class="sect1" id="PLPERL-FUNCS"><div class="titlepage"><div><div><h2 class="title" style="clear: both">43.1. PL/Perl Functions and Arguments <a href="#PLPERL-FUNCS" class="id_link">#</a></h2></div></div></div><p>
3 To create a function in the PL/Perl language, use the standard
4 <a class="xref" href="sql-createfunction.html" title="CREATE FUNCTION"><span class="refentrytitle">CREATE FUNCTION</span></a>
7 </p><pre class="programlisting">
8 CREATE FUNCTION <em class="replaceable"><code>funcname</code></em> (<em class="replaceable"><code>argument-types</code></em>)
9 RETURNS <em class="replaceable"><code>return-type</code></em>
10 -- function attributes can go here
12 # PL/Perl function body goes here
16 The body of the function is ordinary Perl code. In fact, the PL/Perl
17 glue code wraps it inside a Perl subroutine. A PL/Perl function is
18 called in a scalar context, so it can't return a list. You can return
19 non-scalar values (arrays, records, and sets) by returning a reference,
22 In a PL/Perl procedure, any return value from the Perl code is ignored.
24 PL/Perl also supports anonymous code blocks called with the
25 <a class="xref" href="sql-do.html" title="DO"><span class="refentrytitle">DO</span></a> statement:
27 </p><pre class="programlisting">
33 An anonymous code block receives no arguments, and whatever value it
34 might return is discarded. Otherwise it behaves just like a function.
35 </p><div class="note"><h3 class="title">Note</h3><p>
36 The use of named nested subroutines is dangerous in Perl, especially if
37 they refer to lexical variables in the enclosing scope. Because a PL/Perl
38 function is wrapped in a subroutine, any named subroutine you place inside
39 one will be nested. In general, it is far safer to create anonymous
40 subroutines which you call via a coderef. For more information, see the
41 entries for <code class="literal">Variable "%s" will not stay shared</code> and
42 <code class="literal">Variable "%s" is not available</code> in the
43 <span class="citerefentry"><span class="refentrytitle">perldiag</span></span> man page, or
44 search the Internet for <span class="quote">“<span class="quote">perl nested named subroutine</span>”</span>.
46 The syntax of the <code class="command">CREATE FUNCTION</code> command requires
47 the function body to be written as a string constant. It is usually
48 most convenient to use dollar quoting (see <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING" title="4.1.2.4. Dollar-Quoted String Constants">Section 4.1.2.4</a>) for the string constant.
49 If you choose to use escape string syntax <code class="literal">E''</code>,
50 you must double any single quote marks (<code class="literal">'</code>) and backslashes
51 (<code class="literal">\</code>) used in the body of the function
52 (see <a class="xref" href="sql-syntax-lexical.html#SQL-SYNTAX-STRINGS" title="4.1.2.1. String Constants">Section 4.1.2.1</a>).
54 Arguments and results are handled as in any other Perl subroutine:
55 arguments are passed in <code class="varname">@_</code>, and a result value
56 is returned with <code class="literal">return</code> or as the last expression
57 evaluated in the function.
59 For example, a function returning the greater of two integer values
62 </p><pre class="programlisting">
63 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
64 if ($_[0] > $_[1]) { return $_[0]; }
68 </p><div class="note"><h3 class="title">Note</h3><p>
69 Arguments will be converted from the database's encoding to UTF-8
70 for use inside PL/Perl, and then converted from UTF-8 back to the
71 database encoding upon return.
73 If an SQL null value<a id="id-1.8.10.9.10.1" class="indexterm"></a> is passed to a function,
74 the argument value will appear as <span class="quote">“<span class="quote">undefined</span>”</span> in Perl. The
75 above function definition will not behave very nicely with null
76 inputs (in fact, it will act as though they are zeroes). We could
77 add <code class="literal">STRICT</code> to the function definition to make
78 <span class="productname">PostgreSQL</span> do something more reasonable:
79 if a null value is passed, the function will not be called at all,
80 but will just return a null result automatically. Alternatively,
81 we could check for undefined inputs in the function body. For
82 example, suppose that we wanted <code class="function">perl_max</code> with
83 one null and one nonnull argument to return the nonnull argument,
84 rather than a null value:
86 </p><pre class="programlisting">
87 CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS $$
90 return undef if not defined $y;
93 return $x if not defined $y;
94 return $x if $x > $y;
98 As shown above, to return an SQL null value from a PL/Perl
99 function, return an undefined value. This can be done whether the
100 function is strict or not.
102 Anything in a function argument that is not a reference is
103 a string, which is in the standard <span class="productname">PostgreSQL</span>
104 external text representation for the relevant data type. In the case of
105 ordinary numeric or text types, Perl will just do the right thing and
106 the programmer will normally not have to worry about it. However, in
107 other cases the argument will need to be converted into a form that is
108 more usable in Perl. For example, the <code class="function">decode_bytea</code>
109 function can be used to convert an argument of
110 type <code class="type">bytea</code> into unescaped binary.
112 Similarly, values passed back to <span class="productname">PostgreSQL</span>
113 must be in the external text representation format. For example, the
114 <code class="function">encode_bytea</code> function can be used to
115 escape binary data for a return value of type <code class="type">bytea</code>.
117 One case that is particularly important is boolean values. As just
118 stated, the default behavior for <code class="type">bool</code> values is that they
119 are passed to Perl as text, thus either <code class="literal">'t'</code>
120 or <code class="literal">'f'</code>. This is problematic, since Perl will not
121 treat <code class="literal">'f'</code> as false! It is possible to improve matters
122 by using a <span class="quote">“<span class="quote">transform</span>”</span> (see
123 <a class="xref" href="sql-createtransform.html" title="CREATE TRANSFORM"><span class="refentrytitle">CREATE TRANSFORM</span></a>). Suitable transforms are provided
124 by the <code class="filename">bool_plperl</code> extension. To use it, install
126 </p><pre class="programlisting">
127 CREATE EXTENSION bool_plperl; -- or bool_plperlu for PL/PerlU
129 Then use the <code class="literal">TRANSFORM</code> function attribute for a
130 PL/Perl function that takes or returns <code class="type">bool</code>, for example:
131 </p><pre class="programlisting">
132 CREATE FUNCTION perl_and(bool, bool) RETURNS bool
133 TRANSFORM FOR TYPE bool
136 return $a && $b;
139 When this transform is applied, <code class="type">bool</code> arguments will be seen
140 by Perl as being <code class="literal">1</code> or empty, thus properly true or
141 false. If the function result is type <code class="type">bool</code>, it will be true
142 or false according to whether Perl would evaluate the returned value as
144 Similar transformations are also performed for boolean query arguments
145 and results of SPI queries performed inside the function
146 (<a class="xref" href="plperl-builtins.html#PLPERL-DATABASE" title="43.3.1. Database Access from PL/Perl">Section 43.3.1</a>).
148 Perl can return <span class="productname">PostgreSQL</span> arrays as
149 references to Perl arrays. Here is an example:
151 </p><pre class="programlisting">
152 CREATE OR REPLACE function returns_array()
153 RETURNS text[][] AS $$
154 return [['a"b','c,d'],['e\\f','g']];
157 select returns_array();
160 Perl passes <span class="productname">PostgreSQL</span> arrays as a blessed
161 <code class="type">PostgreSQL::InServer::ARRAY</code> object. This object may be treated as an array
162 reference or a string, allowing for backward compatibility with Perl
163 code written for <span class="productname">PostgreSQL</span> versions below 9.1 to
166 </p><pre class="programlisting">
167 CREATE OR REPLACE FUNCTION concat_array_elements(text[]) RETURNS TEXT AS $$
170 return undef if (!defined $arg);
172 # as an array reference
177 # also works as a string
183 SELECT concat_array_elements(ARRAY['PL','/','Perl']);
186 </p><div class="note"><h3 class="title">Note</h3><p>
187 Multidimensional arrays are represented as references to
188 lower-dimensional arrays of references in a way common to every Perl
192 Composite-type arguments are passed to the function as references
193 to hashes. The keys of the hash are the attribute names of the
194 composite type. Here is an example:
196 </p><pre class="programlisting">
197 CREATE TABLE employee (
203 CREATE FUNCTION empcomp(employee) RETURNS integer AS $$
205 return $emp->{basesalary} + $emp->{bonus};
208 SELECT name, empcomp(employee.*) FROM employee;
211 A PL/Perl function can return a composite-type result using the same
212 approach: return a reference to a hash that has the required attributes.
215 </p><pre class="programlisting">
216 CREATE TYPE testrowperl AS (f1 integer, f2 text, f3 text);
218 CREATE OR REPLACE FUNCTION perl_row() RETURNS testrowperl AS $$
219 return {f2 => 'hello', f1 => 1, f3 => 'world'};
222 SELECT * FROM perl_row();
225 Any columns in the declared result data type that are not present in the
226 hash will be returned as null values.
228 Similarly, output arguments of procedures can be returned as a hash
231 </p><pre class="programlisting">
232 CREATE PROCEDURE perl_triple(INOUT a integer, INOUT b integer) AS $$
234 return {a => $a * 3, b => $b * 3};
237 CALL perl_triple(5, 10);
240 PL/Perl functions can also return sets of either scalar or
241 composite types. Usually you'll want to return rows one at a
242 time, both to speed up startup time and to keep from queuing up
243 the entire result set in memory. You can do this with
244 <code class="function">return_next</code> as illustrated below. Note that
245 after the last <code class="function">return_next</code>, you must put
246 either <code class="literal">return</code> or (better) <code class="literal">return
249 </p><pre class="programlisting">
250 CREATE OR REPLACE FUNCTION perl_set_int(int)
251 RETURNS SETOF INTEGER AS $$
258 SELECT * FROM perl_set_int(5);
260 CREATE OR REPLACE FUNCTION perl_set()
261 RETURNS SETOF testrowperl AS $$
262 return_next({ f1 => 1, f2 => 'Hello', f3 => 'World' });
263 return_next({ f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' });
264 return_next({ f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' });
269 For small result sets, you can return a reference to an array that
270 contains either scalars, references to arrays, or references to
271 hashes for simple types, array types, and composite types,
272 respectively. Here are some simple examples of returning the entire
273 result set as an array reference:
275 </p><pre class="programlisting">
276 CREATE OR REPLACE FUNCTION perl_set_int(int) RETURNS SETOF INTEGER AS $$
280 SELECT * FROM perl_set_int(5);
282 CREATE OR REPLACE FUNCTION perl_set() RETURNS SETOF testrowperl AS $$
284 { f1 => 1, f2 => 'Hello', f3 => 'World' },
285 { f1 => 2, f2 => 'Hello', f3 => 'PostgreSQL' },
286 { f1 => 3, f2 => 'Hello', f3 => 'PL/Perl' }
290 SELECT * FROM perl_set();
293 If you wish to use the <code class="literal">strict</code> pragma with your code you
294 have a few options. For temporary global use you can <code class="command">SET</code>
295 <code class="literal">plperl.use_strict</code> to true.
296 This will affect subsequent compilations of <span class="application">PL/Perl</span>
297 functions, but not functions already compiled in the current session.
298 For permanent global use you can set <code class="literal">plperl.use_strict</code>
299 to true in the <code class="filename">postgresql.conf</code> file.
301 For permanent use in specific functions you can simply put:
302 </p><pre class="programlisting">
305 at the top of the function body.
307 The <code class="literal">feature</code> pragma is also available to <code class="function">use</code> if your Perl is version 5.10.0 or higher.
308 </p></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="plperl.html" title="Chapter 43. PL/Perl — Perl Procedural Language">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="plperl.html" title="Chapter 43. PL/Perl — Perl Procedural Language">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="plperl-data.html" title="43.2. Data Values in PL/Perl">Next</a></td></tr><tr><td width="40%" align="left" valign="top">Chapter 43. PL/Perl — Perl Procedural Language </td><td width="20%" align="center"><a accesskey="h" href="index.html" title="PostgreSQL 18.0 Documentation">Home</a></td><td width="40%" align="right" valign="top"> 43.2. Data Values in PL/Perl</td></tr></table></div></body></html>