Fake Perl shell
Social links
View Ashley Pond V's profile on LinkedIn
Miscellaneous

Other pages

Description

Many programmers have worked many hours on building a pure Perl shell. This little recipe allows you to execute perl code interactively and acts like the shell. It would need some Term::ReadKey and other good sauce to really be convincing but this is pretty good in a pretty small space.

It’s tremendously useful for testing code interactively in a single terminal window.

This recipe is adapted from one by Dr. Tim Maher who administers the Seattle Perl Users Group (SPUG). The meat of the script is really only 3 or 4 lines and note the “-n” switch on the shebang line.

Code
#!/usr/bin/perl -wn

# the -n switch gives us a loop around the script. the BEGIN block is
# only executed once. it sets up our prompt and turns off the signals
# that could interrupt the script

BEGIN {
# turn off control keys
    $SIG{$_} = 'IGNORE' for keys %SIG;   
# let the user know how to get off this crazy thing.
    print "\n\tType\e[1m exit\e[0m when you are ready to stop.\n";

    $history = 1;
    sub prompt {
        print "\n", $ENV{USER}, '@perl-shell[', $history++, ']>';
    }
    prompt;
}
# the body is executed over and over (each time <> is given). all we
# do is eval the body, and voila, perl-shell behavior

eval;
$@ and warn $@;  # give perl errors back to the user

prompt;                # print a fresh prompt with updated history

END { print "\n\t\tBye!\n\n" }
Usage
jinx[203]>perl-shell

        Type exit when you are ready to stop.

jinx@perl-shell[1]>
jinx@perl-shell[1]>print 22/7
3.14285714285714
jinx@perl-shell[2]>sub big { $text = shift; return `banner $text` }

jinx@perl-shell[3]>monkey

jinx@perl-shell[4]>print bif('monkey') 
Undefined subroutine &main::bif called at (eval 2) line 1, <> line 2.

jinx@perl-shell[5]>print big('monkey')

 #    #   ####   #    #  #    #  ######   #   #
 ##  ##  #    #  ##   #  #   #   #         # #
 # ## #  #    #  # #  #  ####    #####      #
 #    #  #    #  #  # #  #  #    #          #
 #    #  #    #  #   ##  #   #   #          #
 #    #   ####   #    #  #    #  ######     #


jinx@perl-shell[6]>exit

                Bye!

jinx[204]>

Discussion

You may ask, “Why on earth go to the trouble? The debugger does the same thing as easy as perl -de 42.”

Well, you got me. The debugger does much more too. Larry Wall, the creator of Perl who wrote the debugger, however, admits he almost never uses it. Some programmers swear by it but it’s not easy or fun to use. Unless you’re trying to track down memory leaks, namespace problems or other killer bugs, the perl-shell above is a more familiar approach with easier error reporting.

Search these pages via Google
Text, original code, fonts, and graphics ©1990-2008 Ashley Pond V.