Subject: A Perl Expression that evaluates into itself

From: Shlomi Fish <[email-masked]>
Date: Mon, 17 Dec 2001 10:21:00 +0200 (IST)

It's included at the end of this message. (and no it isn't "1" - :-)).
Omer Mussaev challenged me to write it while we were comparing Scheme and
Perl. Eventually, he told me that his lecturer managed to write it in Perl
using pure lambda calculus.

When I wrote it, I had to spend some time on making sure the indentation
would be exactly the same in the two sub-expressions. Omer can supply the
original code in Scheme which inspired this anecdote. I also found a C
program that prints its source code on the screen:

http://www.cip.physik.uni-muenchen.de/~tf/misc/self.c

Best regards,

	Shlomi Fish

use strict;

sub addbackslashes
{
	my $string = shift;
	my $out = "";
	my $char;

	foreach $char (split(//, $string))
	{
		if ($char =~ /[\$\\\"]/)
		{
			$out .= "\\";
		}
		$out .= $char;
	}
	return $out;
}

my $p_expr = & {
	sub {
		my $x = shift;
		return
		"eval {
			my \$local_self ;
			\$local_self = sub {
				&{$x}(\"" . addbackslashes($x) . "\");
			};
			&{\$local_self}();
		}";
	}
	}
(
	"sub {
		my \$x = shift;
		return
		\"eval {
			my \\\$local_self ;
			\\\$local_self = sub {
				&{\$x}(\\\"\" . addbackslashes(\$x) . \"\\\");
			};
			&{\\\$local_self}();
		}\";
	}"
);

my ($a, $b, @array);

my $evaled = eval($p_expr);

print ((($evaled eq $p_expr) ?
	"They are the same." :
	"They are not the same"), "\n");

----------------------------------------------------------------------
Shlomi Fish        [email-masked]
Home Page:         http://t2.technion.ac.il/~shlomif/
Home E-mail:       [email-masked]

"Let's suppose you have a table with 2^n cups..."
"Wait a second - is n a natural number?"