Patch to the pl/perl documents that clarifies the scope of global data and
authorPeter Eisentraut
Sat, 11 Dec 2004 20:03:37 +0000 (20:03 +0000)
committerPeter Eisentraut
Sat, 11 Dec 2004 20:03:37 +0000 (20:03 +0000)
gives an example of storing a code reference

by David Fetter

doc/src/sgml/plperl.sgml

index 7642f50ca45b5c12b76c8dafff0aa7ef70dca82f..a1653a3ac7875d6f6d03db57e784675631621388 100644 (file)
@@ -1,5 +1,5 @@
 
 
  
@@ -315,8 +315,14 @@ $$  LANGUAGE plperl;
   Global Values in PL/Perl
 
   
-   You can use the global hash %_SHARED to store
-   data between function calls.  For example:
+    You can use the global hash %_SHARED to store
+    data, including code references, between function calls for the
+    lifetime of the current session, which is bounded from below by
+    the lifetime of the current transaction.
+  
+
+  
+    Here is a simple example for shared data:
 
 CREATE OR REPLACE FUNCTION set_var(name text, val text) RETURNS text AS $$
     if ($_SHARED{$_[0]} = $_[1]) {
@@ -334,6 +340,34 @@ SELECT set_var('sample', 'Hello, PL/Perl!  How's tricks?');
 SELECT get_var('sample');
 
   
+
+  
+   Here is a slightly more complicated example using a code reference:
+
+
+CREATE OR REPLACE FUNCTION myfuncs() RETURNS void AS $$
+    $_SHARED{myquote} = sub {
+        my $arg = shift;
+        $arg =~ s/(['\\])/\\$1/g;
+        return "'$arg'";
+    };
+$$ LANGUAGE plperl;
+
+SELECT myfuncs(); /* initializes the function */
+
+/* Set up a function that uses the quote function */
+
+CREATE OR REPLACE FUNCTION use_quote(TEXT) RETURNS text AS $$
+    my $text_to_quote = shift;
+    my $qfunc = $_SHARED{myquote};
+    return &$qfunc($text_to_quote);
+$$ LANGUAGE plperl;
+
+
+   (You could have replaced the above with the one-liner
+   return $_SHARED{myquote}->($_[0]);
+   at the expense of readability.)
+