Source files which work with perl, python, and ruby

One can write a single source code file which works unmodified with all of perl, python, and ruby.

This polyglot code

#=====================================================================
0 and eval('false') and length <<2;
"""  #"
2
BEGIN{ 0 or eval('package _TMP; use Filter::Simple sub {
  my $wipe = sub { my $x="$1"; $x=~ tr/\n/ /c; $x };
  s{^(.*?\n__Perl_code__[^\n]*)}{&$wipe($1)}se;
  s{(\n__Python_code__.*?\n#____END____[^\n]*)}{&$wipe($1)}se;
  }; import _TMP; undef(%_TMP::);'); }
#=====================================================================

def hello()
  print "Hi there ruby!\n";
end
hello();

#=====================================================================
__Perl_code__ = <<'#____END____';
#=====================================================================

sub hello {
  print "Hi there perl!\n";
}
hello();

#=====================================================================
__Python_code__ """  #"
#=====================================================================

def hello() :
  print "Hi there python!"
hello();

#=====================================================================
#____END____
#=====================================================================
yields this
$ perl -w file.ppr; ruby -w file.ppr; python file.ppr 
Hi there perl!
Hi there ruby!
Hi there python!
At least with perl 5.6.0, ruby 1.6.4, and python 1.5.2. All rather old.

Notes

One can repeat this construct multiple times in a file.
The #=====================... lines are merely decorative. Short code fragments may be clearer without them.

Here is a cruftier version which also does Tcl, C, and C++. ;)

The Polyglot List is a collection of less serious polyglots.


Mitchell N Charity <mncharity@vendian.org>
Notes:
 In the absence of interest, further work here is unlikely.

Doables:
 Test with more recent language versions.
 Add design notes and discussion.
 Test embedded doc formats.
 Explore having common variables.
 Create ruby wiki page?
 Change python example to  print "Hi there python!\n",  ?
 Mention smart multi-language weavers.

Versions:
 2003-Sep-01  Repeatable; appearance changes.
 2003-Aug-28  Avoids defining "length"; simplified leading test.
 2003-Aug-26

History:
 2004-Jun-14  Added keyword polyglot, link to Polyglot list.
 2004-Feb-19  Added link to new, bigger mutant.
 2003-Sep-01  A cleaned-up version.
 2003-Aug-28  Created this page.
 2003-Aug-26  First version written.