Prev - Index

Perl examples

A random .signature creator

This script, when run from a cron job, periodically chooses a random quote from a quotes database and creates a new ~/.signature file for my e-mail.


#!/usr/bin/perl
#
# my random signature generator
# Written by Graeme Cross

$home = "/home/graeme";		# the home directory for quote & sig files

open(QUOTES, "$home/.quotes") || die "Can't open quotes file!\n";
while (<QUOTES>) {
  chop;
  push(@quotes, $_);
}
close(QUOTES);

$size = @quotes;

if ($#ARGV < 0) {
  srand(time || $$);		# seed the random number generator
  $r = int(rand($size));	# select a random quote
} else {
  $r = int($ARGV[0]) - 1 ;
  if ($r < 0) {
    $r = 0;
  }
}

$realnum = $r + 1;

open(OUT, ">$home/.signature") || die "Can't open sig file!\n";

print OUT<<Output;
--
Graeme Cross -- Water Studies Centre, Monash University

Random thought #$realnum (Collect all $size)
$quotes[$r]
Output

close(OUT);

# eof

And a ~/.signature file generated by the script would look like this:

    --
    Graeme Cross -- Water Studies Centre, Monash University

    Random thought #17 (Collect all 123)
    Unix IS user friendly. It's just selective about who its friends are.

A URL grabber

This script matches against any http:// URL and displays the hostname. For example:

    echo "http://www.wsc.monash.edu.au/people/gcross/index.html" | grab.pl

would yield the hostname "www.wsc.monash.edu.au".

This is a good workout for Perl's stdin file handling and regular expression matching facilities.


#!/usr/bin/env perl
#
# grab.pl - strip out hostnames from a Netscape bookmarks file (from stdin)
# written by Graeme Cross

while(<STDIN>)
{
  if (/(http:\/\/)+([\w\d\.\-]+(:\d+)*)[\"\/]/i) {
     print "$2\n";
  }
}

Prev - Index