Perl versus PostScript


This compares the basic programming structures for   loops,   arrays,   associative arrays,   branching,   local variables,   subroutines,   require   and   debugging   of Perl and PostScript.

The two languages differ most obviously in punctuation, and in word order (PostScript is of course stack-based). They are similarly (i.e. very) concise :-)


# Perl loops $i = 1; while () { $i++; if ($i > $n) { last; } } # or for $i (0..9) { &do_something($i); } # or foreach (@an_array) { # the array element is in $_ &do_something($_); } % PostScript loops /i 1 def { /i i 1 add def i n gt { exit } if } loop % or 0 1 9 { % that's initial, increment, limit % the loop variable is now on the stack do_something } for % or an_array { % the array element is now on the stack do_something } forall
# Perl arrays @b = (4, 3, 2, 1, 'bang'); $n = scalar @b; # sets n to 5 $a = $b[4]; $b[4] = 'whimper'; foreach $x (@b) { } % PostScript arrays /b [4 3 2 1 (bang)] def /n b length def % sets n to 5 /a b 4 get def b 4 (whimper) put b { /x exch def } forall
# Perl associative arrays %phonenums = ('Fred', '1234 5678', 'Gina', '2345 6789'); $x = $phonenums{'Gina'}; $phonenums{'Harry'} = '3456 7890'; while (($key,$value) = each %phonenums) { &do_something($key,$value); } % Level 2 PostScript dictionaries /phonenums << (Fred) (1234 5678) (Gina) (2345 6789) >> def /x phonenums (Gina) get def phonenums (Harry) (3456 7890) put phonenums { do_something % the key and value are on the stack } forall
# Perl branching if ($i > $n) { } else { } % PostScript branching i n gt { } { } ifelse
# Perl local variables { local ($i,$j) = 1,1; } % PostScript begin a new current dictionary 10 dict begin % this can hold up to ten new local variables /i 1 def /j 1 def end
# Perl subroutines sub do_something { my ($arg1, $arg2, $arg3) = @_; $some_result = 42; return $some_result; } $x = &do_something($arg1, $arg2, $arg3); % PostScript procedures /do_something { 20 dict begin % this can hold up to twenty new local variables [ /arg3 /arg2 /arg1 ] { exch def } forall /some_result 42 def some_result % now it's on the stack end } def /x arg1 arg2 arg3 do_something def
# 'requiring' a Perl library require '/home/fred/pl/a_library.pl'; % 'running' a PostScript file (assuming of course there is a filesystem) (/home/fred/ps/a_library.ps) run
# debugging a Perl script warn "my_subroutine: gloop=$gloop gleep=$gleep\n"; % debugging a PostScript file (my_subroutine: gloop=) = gloop == (gleep=) == gleep == flush pstack % dumps the stack (starting at the top) leaves the stack unchanged % you may want to use the command: gs -dNODISPLAY foo.ps

References: Programming Perl, Larry Wall, Tom Christiansen and Randall Schwartz, O'Reilly, 1996, and the PostScript Language Reference Manual, Adobe Systems Incorporated, Addison Wesley, 1991.
See also www.faqs.org/faqs/postscript/faq/


Back to P J B Computing or to www.pjb.com.au . . .