4

Tip #404   An interactive perl shell

I've long been frustrated by the lack of an interactive perl shell, where I can enter commands and see the results immediately. Yes, I have tried the perl debugger.

#!perl

use strict;
no strict 'vars';
no strict 'refs';
use warnings;

use Data::Dumper;
$Data::Dumper::Indent--;

$| = 1;

# an alias for exit()
sub quit { exit; }

my ($ver,$maj,$min) = ($] =~ /(\d+)\.(\d{3})(\d{3})/);
$maj += 0;
$min += 0;
print +(split '/', $^X)[-1], " $ver.$maj.$min\n";

$, = ',';
$THE_PROMPT = '% ';
print $THE_PROMPT;
while (<>) { print eval; print +($@ || "\n") . $THE_PROMPT };

Caveats:
- you have to enter complete commands on a single line
- because each 'eval'ed line is printed, if the result is undefined you'll get a "Use of uninitialized value" warning

Usage:
- naturally, I create a bash alias for the script
- this is cygwin on winxp, hence the "perl.exe" in the output below

$ alias perlsh='perl ~/bin/perlsh.pl'
$ perlsh
perl.exe 5.10.0
% @l=qw(the quick brown fox jumps over the lazy dog)
the,quick,brown,fox,jumps,over,the,lazy,dog
% @sorted_by_length = map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, length]} @l
the,fox,the,dog,over,lazy,quick,brown,jumps