TPJ One Liners

Short bits of code which will amaze, awaken, and amuse.


August 12, 2001
URL:http://www.drdobbs.com/web-development/tpj-one-liners/184416234

TPJ One-Liners - The Perl Journal


#1

Adding a long list of numbers on the command line:
perl -e 'print eval join("+", @ARGV)' 6 10 20 11
9 16 17 28 100 33333 14 -7

appeared in Issue 7


#2

A cheap alarm clock:
perl -e 'sleep(120); while (1) { print "\a" }'

appeared in Issue 7


#3    Using Perl from Emacs

To apply a Perl expression EXPR to a region:
C-u M-| perl -pe 'EXPR'
To apply EXPR to the entire buffer:
C-x h C-u M-| perl -pe 'EXPR'

Courtesy of Mark-Jason Dominus.
appeared in Issue 8


#4    Preserving case in a substitution

To replace substring $x with an equal length substring $y, but preserving the case of $x:Z

$string =~ s/($x)/"\L$y"^"\L$1"^$1/ie;

Courtesy of Dean Inada
appeared in Issue 8


#5    Exploiting the F00F Pentium bug

require DynaLoader;
DynaLoader::dl_install_xsub("main::hangme",
         unpack("I", pack("P4", "\xF0\x0F\xC7\xC8")));
hangme();
Do NOT execute this. It will crash your computer.

Courtesy of Gisle Aas
appeared in Issue 8


#6    Primality

perl -le 'print "PRIME" if (1 x shift) !~ /^(11+)\1+$/' 19
Type this from your command line to test whether 19 (or any other integer of your choosing) is prime.

Courtesy of Abigail, [email protected]
appeared in Issue 8


#7    An Absurd Way To Convert From Decimal To Binary

#!/usr/bin/perl

($decimal, $binary) = (shift, '');
$SIG(USR1) = sub { $binary .= "0"};
$SIG(USR2) = sub { $binary .= "1"};

do { kill $decimal & 1 ? 'USR2' : 'USR1' , $$;
     $decimal >>= 1;
} while ($decimal);

print scalar reverse $binary;



Courtesy of Nathan Torkington
appeared in Issue 9


#8    How To Patch Your Netscape Binary To Enable Strong Encryption

#!/usr/bin/perl -0777pi
s/TS:.*?\0/$_=$&;y,a-z, ,;s,    $,true,gm;s, 512,2048,;$_/es

Courtesy of Ian Goldberg
appeared in Issue 9


#9    How To Use The Perl Debugger as a Command-Line Interpreter

perl -de 0

appeared in Issue 9


#10    Using PDL to Generate Fractals

Using PDL to Generate Fractals
use PDL; use PDL::IO::Pic;$a=zeroes 300,300;
$r=$a->xlinvals(-1.5,0.5);$i=$a->ylinvals(-1,1);
$t=$r;$u=$i;for(1..30){$q=$r**2-$i**2+$t;$h=2*$r*$i+
$u;$d=$r**2+$i**2;$a=lclip($a,$_*($d>2.0)*($a==0));($r,
$i)=map{$_->clip(-5,5)}($q,$h);}$a->wpic("mandel.gif");

Courtesy of Tuomas J.Lukka
appeared in Issue 9




TPJ One-Liners - The Perl Journal


#11    The Game Of Life

The Game Of Life
use PDL; use PDL::Image2D;
use PDL::Graphics::TriD;nokeeptwiddling3d;
$d=byte(random(zeroes(40,40))>0.85);
$k=byte [[1,1,1],[1,0,1],[1,1,1]];
do{ imagrgb [$d]; $s=conv2d($d,$k);
$d&=($s>4);$d&=($s>1);$d|=($s==3);}
while (!twiddle3d);

Courtesy of Robin Williams
appeared in Issue 10


#12    DeMorgan's Rule

if (!$a || $b != $c) { ... }
is equivalent to
unless ( $a && $b == $c ) { ... }

appeared in Issue 10


#13

Little-known facts about qr// (new with Perl 5.005): it has a magic print value, and it's an object of type Regexp.

% perl -le 'print "My regex: ", qr/^watch/i'
                               My regex: (?i-xsm:^watch this)
                               
                            $rob = qr/red/i;
                            if ($rob->match("Fred Flintstone")) {
                                print "Got obj fred!\n";
                            }

                            sub Regexp::match {
                                my $self = shift;
                                my $arg = @_ ? shift : $_;
                                return $arg =~ /$arg/;
                            }

Courtesy of Tom Christiansen
appeared in Issue 11


#14

Transpose a two-dimensional array:
@matrix_t = map{my$x=$_;[map {$matrix[$_][$x]}
0..$#matrix]}0..$#{$matrix[0]};

Courtesy of Tuomas J. Lukka
appeared in Issue 11


#15    Primality

Primality
use PDL; use PDL::Graphics::TriD; $s=40;$a=zeroes
2*$s,$s/2;$t=$a->xlinvals(0,6.284);$u=$a->ylinvals
(0,6.284);$o=5;$i=1;$v=$o-$o/2*sin(3*$t)+$i*sin$u;
imag3d([$v*sin$t,$v*cos$t,$i*cos($u)+$o*sin(3*$t)]);

Courtesy of Tuomas J. Lukka
appeared in Issue 11


#16

This code converts any GIF to an HTML table--each cell of the table corresponds to a pixel of the image. Use this to make your web advertisements seem like important content and circumvent Lincoln's Apache::AdBlocker. :

This code is online at http://tpj.com/one-liners.
use GD;$f='#ffffff';$T=table;sub p{print @_}
p"<body bgcolor=$f>";for(@ARGV){open*G,$_ or(warn("$_:
$!")&&next);$g=GD::Image->newFromGif(G)||(warn$_,
": GD error"and next);@c=map{$_!=$g->transparent
?sprintf'#'.('%.2x'x3),$g->rgb($_):$f}0..
$g->colorsTotal;p"<$T border=0 cellpadding=0
cellspacing=0>";($x,$y)=$g->getBounds;for$j(0..$y)
{p"<tr>";for($i=0;$i<$x;$i++){$s=1;$s++&&$i++while($i+1
<$x&&$g->getPixel($i+1,$j)==$g->getPixel($i,$j));p"
<td bgcolor=",$c[$g->getPixel($i,$j)],"
colspan=$s> "}}p"</$T>"}

Courtesy of Mike Fletcher
appeared in Issue 11


#17

Ever wish backquotes didn't interpolate variables? qx() is a synonym for backquotes, but if you use single quotes as a delimiter, it won't interpolate: qx'echo $HOME' works.

Courtesy of Tom Christiansen
appeared in Issue 11


#18

"Use m//g when you know what you want to keep, and split() when you know what you want to throw away."

Courtesy of Randal L. Schwartz
appeared in Issue 11


#19

Count the lines of pod and code in a Perl program:

@a=(0,0);while(<>){++$a[not m/
^=\w+/s .. m/^=cut/s]} printf"%d
pod lines, %d code lines\n",@a;

Courtesy Sean M. Burke
appeared in Issue 11


#20    Results of the SunWorld reader survey (4,106 respondents)

Which of the following open source products do you have installed for WORK use?


Perl            83%
Sendmail        74%
Apache          72%
Linux           64%
Tcl             52%
Python          24%

Which of the following open source products do you have installed for PERSONAL use?

Perl            79%
Linux           77%
Apache          63%
Sendmail        61%
Tcl             55%
Python          34%

appeared in Issue 11




TPJ One-Liners - The Perl Journal


#21

Picking random elements from an array:

srand;
$item = $array[rand @array];

appeared in Issue 12


#22

If you're trying to get Windows to generate a PostScript file, but it wraps the file with PCL junk, you can remove it with this:

perl -ni -e "!$g&&s/^.*(%!.*)/$1/&&$g or print;last if /^%%
EOF/"

appeared in Issue 12


#23

In the movie Sphere, the commands that Harry typed to translate the message were taken from Tom Christiansen's FAQ:

$BSD = -f '/vmunix'; if ($BSD) {system "BIN
cbreak </dev/tty >/dev/tty 2>&1
sub set_break { # &setset_cbreak(1) or &set_cbreak(0)
                        local($on) = $_[0];
			      local($sgttyb,@ary);
			      require 'sys/ioctl.ph';


Courtesy of Brendan O'Dea
appeared in Issue 12


#24

Seperate the header and body of a mail message into strings

while (<>)  {
    $in_header =   1  ../^$/;
        $in_body   = /^$/ ..eof();

Courtesy of the Perl Cookbook
appeared in Issue 12


#25

Simple numeric tests:

warn "has nondigits" if /\D/;
warn "not a natural number" unless /^\d+$/;
warn "not an integer" unless /^'?\d+$/;
warn "not an integer" unless /^[+']?\d+$/;
warn "not a decimal number" unless
             /^'?\d+\.?\d*$/; # rejects .2
warn "not a decimal number" unless
             /^'?(?:\d+(?:\.\d*)?|\.\d+)$/;
warn "not a C float" unless
             /^([+']?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;


Courtesy of The Perl Cookbook
appeared in Issue 12


#26

Launching xterms with random colors. You might have to replace xterm with whatever command you use to launch a terminal window:

perl -e '$fg=rand 2**24; do { $bg = rand
2**24 } while (unpack("%32b*", pack "N",
($bg^$fg)&0xe0e0e0) < 8); ($fg, $bg) =
map { sprintf "#%06x", $_ } $fg, $bg;
exec("xterm", "-fg", $fg, "-bg", $bg);'

Courtesy of Tkil
appeared in Issue 12


#27

Lop off the latter half of an array:

$#array /= 2;

Courtesy of The Perl Cookbook
appeared in Issue 12


#28

perl -0nal012e '@a{@F}++; print for sort keys %a'
Extracts, sorts, and prints the words from a file.

Courtesy of Peter J. Kernan
appeared in Issue 13


#29

This subroutine accepts a string and returns a true value if all of the parentheses, brackets, and braces in the string are balanced.

sub is_balanced {
                         my $it = $_[0];
                         $it =~ tr/()[]{}//cd;
                         while ($it =~ s/\(\)|\[\]|\{\}//g) { 1 }
                         return !length($it);
                      }



Courtesy Sean M. Burke
appeared in Issue 13


#30

"Regular expressions are to strings what math is to numbers."

--Andrew Clinick, discussing what Microsoft thinks of Perl

in http://msdn.microsoft.com/library/en-us/dnclinic/html/scripting012299.asp.

Short answer: They like it.

Anonymous
appeared in Issue 13




TPJ One-Liners - The Perl Journal


#31

perl -e  'print "Internet Time @",
  int (((time + 3600) % 86400)/86.4), "\n";'
Swatch's Internet Time, heralded as a revolutionary way
of measuring time independent of geography. See
http://www.swatch.com for details.

Anonymous
appeared in Issue 13


#32    A trick for indenting here strings

($definition = <<'FINIS') =~ s/^\s+//gm;
    The five varieties of camelids are the familliar
    camel, his friends the llama and the alpaca, and
    the rather less well-known guanaco and vicuna.
FINIS

Courtesy of The Perl Cookbook
appeared in Issue 13


#33

Efficiently finding the position of the first and last
occurrences of a substring in a string

$first = index($string, $substring);
$last = rindex($string, $substring);

appeared in Issue 13


#34

Some scalars that Perl defines for you:

$^O contains the name of your operating system.
$^T contains the time at which your program began.
$O contains the name of your program

appeared in Issue 13


#35    If Dr. Seuss were a Perl programmer

#!/usr/bin/perl
# 
# Will give errors if run with -w, so don't use -w :)
# Tested on NT with AS (5.005), GS (5.004_02), 
# and Solaris 2.6 (5.004_04)

if ("a packet hits a pocket") {
    On: a;
    socket(ON, A ,PORT,"")
           && the bus is interrupted as a very-last-resort
           && the address of the memory makes your 
              floppy disk, abort;
		
} else {

    "The socket packet pocket has an";
    error: to-report;
} 

if ("your cursor finds a menu item") { 
    "followed by a dash"
            && "the double clicking icon";
    puts: your-items-in-the-trash
            && your data is corrupted cause the 
               index("doesn't", "hash");

} else {
   "Your situation is hopeless"
            && Your system's gonna crash;
} 

if ("the label on the cable") {
    On-the-table, at-your-house;
    Says_the; 
    sub network {"is connected to the button on your mouse"};
    BUT: Your-packets, want-to; 
    {/tunnel to another protocol/};
    that's: repeatedly-rejected; 
    {/by the printer/}; "down the hall"
            && "YOUR SCREEN is all distorted";
    {/by the side effects of Gauss/};
    so: "your icons", in-the-window;
    "are as wavy as a souse";

} else {
    YOU: "may as well reboot" && "go out with a !";
    CAUSE: /Sure as Im a poet/;
    THIS: suckers-gonna-hang;
}

print "Seuss as a tech writer - Kevin Meltzer\n"; 

Courtesy of Kevin Meltzer
appeared in Issue 14


#36

Neal Stephenson's latest novel, Cryptonomicon, includes a Perl cryptosystem code-named Pontifex. You can read about it at http://www.well.com/user/neal/cypherFAQ.html#12.

appeared in Issue 14


#37

Stripping the eighth bits from a string $s &= "\177" x length($s); Given a string in $s, this one-liner turns all of the "funny" characters (like or ) into regular seven-bit ASCII characters. It works by ANDing the bit representation of each character with 127, which removes the eighth bit. That turns into L and into N, for instance.

Courtesy of Tom Christiansen
appeared in Issue 14


#38

Replacing tabs with spaces

perl -0011 -pi -e '/\011/&apm;&($_="$'")' filename

Courtesy of Abigail
appeared in Issue 14


#39

Printing all capitalized words

perl -ne 'push@w,/(\b[A-Z]\S*?\b)/g;END{print"@w"}' file

appeared in Issue 14




TPJ One-Liners - The Perl Journal


#40

A name game.

s<^([bcdfghjklmnpqrstvwxyz]*)(\w+).*>
<$1$2 $1$2 $1o $1$2 / Bonana-Fanna-Fo-F$2 / 
Fe Fi Mo M$2 / $1$2!>i;

Courtesy of Sean M. Burke
appeared in Issue 15


#41

Extracting balanced parentheses from a string

use strict
              ;sub                  pars
            {my(                     $l,$r
          )=map{                       "\Q$_"
        }split//                        ,shift;
      my(@s,@r                            ,$i,$o,
     $v);for(                             split/([
    $l$r])/,                                shift){
    /$l/and                                $s[++$o]=
   ++$i;for                                $v(1..$o)#
   {$r[$v].=                              $_ if$s[$v]
    >0}/$r/and                            $s[(grep##
     $s[$_]==                            $i,0..$#s)
      [0]]=-$i         ,--$i<0&&        last;}($i=
        shift)?        wantarray       ?@r[grep
          -$s[$_       ]==$i,0..       $#s]:$r
            [$i]:      splice@r,      1;}$,
              ="\n"     ;print       pars
                 (@      ARGV       )#

pars('()', "(123 (456) (789) 0)")

gives you the parenthesized substrings in order of appearance:

(123 (456) (789) 0),(456),(789)
pars('()', "(123 (456) (789) 0)", 2)

in a list context gives you list of substrings, opened on level 2:

(456),(789)

in scalar context gives you the second substring:

(456)

Courtesy of Paul Clinger
appeared in Issue 15


#42

Extract unique elements from a list given a key function

sub unique (&@) {
  my($c,%hash) = shift;
  grep { not $hash{&$c}++ } @_
}

@list = unique { $_       } @list;  
# Remove duplicate strings from @list.

@obj  = unique { $_->name } @obj;   
# Only include one object for 
# for each name.

Courtesy of Don Schwarz
appeared in Issue 15


#43

Seven "Magic Cards." Have a friend think of a number from 1 to 100. Give them cards one at a time and ask if their number is on the card. Mentally sum the first digits of each card with a "yes" answer. Go into trance, say the magic word "Ultrix!" and announce their number. Known to win bar bets.

for $a(0..6){$b=1;for $c(1..100){if($c&2**$a){printf
"%3d ",$c;print"\n"if!($b++%10)}}print"\n\n\n"}

Courtesy of Bill Huston
appeared in Issue 15


#44

Asteroid 2000 BF19 was thought to be on a potentially dangerous approach path for us Terrans, with a possible impact in 2022. A Perl program called clomon.pl showed that the asteroid cannot come any closer than 0.038 AU for the next fifty years. Sleep tight!

-Based on email from Andrea Milani and Scott Manley
appeared in Issue 17


#45

Tracking the progress of a file as it downloads:

perl -e 'BEGIN{$|=1;$f=$ARGV[0];$s=(stat$f)[7];$t=time}
	    while(sleep 1){printf"\r$f %s bytes at %.2f Kb/s   ",
        $_=(stat$f)[7],($_-$s)/1024/(time-$t)}' 

your_downloading_file

-Courtesy Philippe Bruhat
appeared in Issue 17


#46

A full list of installed (but nonstandard) modules, and where they are located:

#!/usr/bin/perl -w
use strict;                            # all variables must be declared
use Getopt::Std;                       # import the getopts method
use ExtUtils::Installed;               # import the package

use vars qw($opt_l $opt_s);            # declaring the two option switches
&getopts('ls');                        # $opt_l and $opt_s are set to 1 or 0
unless($opt_l or $opt_s) {             # unless one switch is true (1)
  die "pmods: A utility to list all installed (nonstandard) modules\n",
      "  Usage: pmods.pl -l  # list each module and all its directories\n",
      "        pmods.pl -s  # list just the module names\n";
}

my $inst  = ExtUtils::Installed->new();
foreach my $mod ( $inst->modules() ) { # foreach of the installed modules
  my $ver = $inst->version($mod);      # version number of the module
     $ver = ($ver) ? $ver : 'NONE';    # for clean operation
  print "MODULE: $mod version $ver\n"; # print module names
  map { print "  $_\n" } $inst->directories($mod) if($opt_l);
}

-Courtesy William H. Asquith et al.
appeared in Issue 17


#47

Print a message if a daylight savings time change occurs within the next 5 days:

print "\aTIME CHANGE COMING!\n"
    if (localtime(time))[8] ne (localtime(time+5*24*60*60))[8];

-Courtesy J.D. Laub


#48

Reverse for syntax to print out Perl's include path:

perl -e 'print "$_\n" for @INC'

appeared in Issue 17


#49

You can create a reference to a scalar like so:

   $ref = \$var;

In recent versions of Perl, you can also say:

   $ref = *var{SCALAR};

The same holds for other data types.

appeared in Issue 17




TPJ One-Liners - The Perl Journal


#50

Upcoming in Perl 5.6:

A new keyword, our, which is like my but is package-aware.

appeared in Issue 17


#51

$^O contains the name of your operating system.

appeared in Issue 17


#52

The Data::Dumper module, bundled with Perl, can save data structures to disk as strings that can be read in by another program.

appeared in Issue 17




Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.