PL/Perl allows writing PostgreSQL functions in Perl. As a trusted language, it runs in a restricted environment without access to the filesystem or external modules.
CREATEEXTENSIONplperl;-- Simple scalar function
CREATEFUNCTIONperl_hello(text)RETURNStextLANGUAGEplperlAS$$my($name)=@_;return"Hello, $name!";$$;SELECTperl_hello('world');-- Using Perl regex for text processing
CREATEFUNCTIONclean_whitespace(text)RETURNStextLANGUAGEplperlAS$$my($str)=@_;$str=~s/^\s+|\s+$//g;#trim$str=~s/\s+//g;#collapseinternalwhitespacereturn$str;$$;-- Returning a composite type
CREATETYPEname_partsAS(first_nametext,last_nametext);CREATEFUNCTIONsplit_name(text)RETURNSname_partsLANGUAGEplperlAS$$my($full)=@_;my($first,$last)=split(/\s+/,$full,2);return{first_name=>$first,last_name=>$last};$$;-- Set-returning function
CREATEFUNCTIONperl_generate_series(integer,integer)RETURNSSETOFintegerLANGUAGEplperlAS$$my($start,$stop)=@_;formy$i($start..$stop){return_next($i);}returnundef;$$;-- Trigger function
CREATEFUNCTIONperl_audit_trigger()RETURNStriggerLANGUAGEplperlAS$$$_TD->{new}{modified_at}=localtime();return"MODIFY";$$;
Database access uses spi_exec_query:
CREATEFUNCTIONperl_row_count(text)RETURNSintegerLANGUAGEplperlAS$$my($table)=@_;my$rv=spi_exec_query("SELECT count(*) AS cnt FROM $table");return$rv->{rows}[0]{cnt};$$;