diff --git a/src/pl/plperl/Makefile.PL b/src/pl/plperl/Makefile.PL
index fc8b25debd437b9caa9abe1f5065c99153ec8d14..5d07bd9a81f1b74e8ba36873479031fd04d75d78 100644
--- a/src/pl/plperl/Makefile.PL
+++ b/src/pl/plperl/Makefile.PL
@@ -3,6 +3,31 @@ use ExtUtils::Embed;
 use DynaLoader;
 use Config;
 
+#
+# Can't build a shared plperl unless libperl is shared too.
+# (Actually, it would be enough if code in libperl.a is compiled
+# to be position-independent, but that is hard to check for and
+# seems pretty unlikely anyway.)
+#
+if ($Config{'useshrplib'} ne 'true') {
+	open(OUT, ">Makefile") or die "Can't write Makefile: $!\n";
+	print OUT <<'EndOfMakefile';
+# Dummy Makefile for use when we can't build plperl
+
+all install:
+	@echo "Cannot build plperl because libperl is not a shared library; skipping it."
+
+clean distclean:
+	rm -f Makefile
+
+.DEFAULT dep depend:
+
+EndOfMakefile
+	close(OUT);
+	exit(0);
+}
+
+
 #
 # get the location of the Opcode module
 #
@@ -25,9 +50,12 @@ my $opcode = '';
 
 }
 
+my $perllib = "-L$Config{archlibexp}/CORE -lperl";
+my $dynalib = "$Config{archlibexp}/auto/DynaLoader/DynaLoader.a";
+
 WriteMakefile( 'NAME' => 'plperl', 
-	dynamic_lib => { 'OTHERLDFLAGS' => "$opcode -L\$(LIBPQDIR) -lpq @{[ldopts()]}" } ,
-	INC => '-I$(LIBPQDIR) -I$(SRCDIR)/include -I$(SRCDIR)/backend',
+	dynamic_lib => { 'OTHERLDFLAGS' => "$opcode $perllib $dynalib" } ,
+	INC => '-I$(SRCDIR)/include -I$(SRCDIR)/backend',
 	XS => { 'SPI.xs' => 'SPI.c' },
 	OBJECT => 'plperl.o eloglvl.o SPI.o',
 	);
@@ -41,6 +69,24 @@ include $(SRCDIR)/Makefile.global
 
 }
 
+sub MY::cflags {
+    package MY;			# so that "SUPER" works right
+    my $inherited = shift->SUPER::cflags(@_);
+
+#
+# Hack for building on HPUX (probably should have a general mechanism
+# for system-specific hints, but for now ...)
+# The default compiler and flags on this platform is cc -Aa, which
+# will reject 'long long' declarations that appear in Postgres headers.
+# Need to select -Ae instead.
+#
+    if ($Config::Config{'osname'} eq 'hpux') {
+	$inherited =~ s/-Aa/-Ae/;
+    }
+
+    $inherited;
+}
+
 sub MY::install {
 
 q[
@@ -49,5 +95,3 @@ install :: all
 ];
 
 }
-
-