A Programming Primer

Show Languages:
Bourne Shell C Shell Perl C Visual Basic Applescript

How to Test for the Number of Arguments | How to Assign Arguments to a Variable | How to Test if a Variable is Set | How to Test if a Variable is Not Set | How to Test if a Variable is Null | How to Set a Default Value for an Argument/Variable | How to Test for Successful Completion of a Command | How to Define and Call Functions/Subroutines | How to Get Input from the User | How to Capture the Output of a System Call | How to construct for loops | How to construct while loops | How to construct case statements | How to use goto commands | How to do Mathematical Calculations | How to Redirect Standard Out and Standard Error | Links

Top How to Test for the Number of Arguments
LanguageExamplesComments
Bourne Shellif [ $# = 0 ] then echo "Usage: $0 [arg-list]" exit 1 fi
C Shellif ($#argv == 0) then echo "Usage: $0 [arg-list]" exit 1 endif x
Perlif (@ARGV < 1) { printf "\nUSAGE: $0 [arg-list]\n"; exit 1; }
Cint main(int argc, char **argv) { if (argc <= 1) { printf("USAGE: argv[0] [arg-list]\n"); exit(1); } }
Visual Basic
Applescript
Top How to Assign Arguments to a Variable
LanguageExamplesComments
Bourne Shellfoo=$1
C Shellset foo=$1 setenv DUMMY $1 Normal variables. Environment variables.
Perl$dummy = $_[0]; $dummy = $ARGV[0]; $dummy = $QUERY->param('foo'); First argument to a command-line Perl script. First argument to a subroutine. Argument named "foo" to a Perl/CGI script.
Cstrcpy(filename, argv[1]);
Visual Basic
Applescripton run argv set foo to item 1 of argv end run
Top How to Test if a Variable is Set
LanguageExamplesComments
Bourne Shellif [ "$foo" ] then echo "'$foo' is set." fi
C Shellif ($?foo != 0) then echo \$foo is set. endif
Perlif ($foo) { print "\$foo is $foo\n"; }
C
Visual Basic
Applescript
Top How to Test if a Variable is Not Set
LanguageExamplesComments
Bourne Shellif [ -z "$foo" ] then echo \$foo is null or not set. fi You cannot tell whether it is null or simply not set. See this example to detect if it's null.
C Shellif ($?foo == 0) then echo \$foo is not set. endif
Perl In "strict" mode, you will get an error if you try to test a variable that is not set (undefined).
C
Visual Basic
Applescript
Top How to Test if a Variable is Null
LanguageExamplesComments
Bourne Shellif [ ! "$foo" ] then echo "'$foo' is null." fi
C Shellif ($foo == "") then echo "'$foo' is null." endif You will get an error if $foo is not set! See this example to check if a variable is set.
Perlif (!($foo)) { print "\$foo is null\n"; } You will get an error in "strict" mode if $foo is not set (undefined)!
C
Visual Basic
Applescript
Top How to Set a Default Value for an Argument/Variable
LanguageExamplesComments
Bourne Shellfoo=${1:-"Default"}
C Shellset foo=$1 if ($?foo == 1) then if ($foo == "") then set foo="Default" endif endif
Perlmy $foo = $ARGV[0] || "Default";
C
Visual Basic
Applescript
Top How to Test for Successful Completion of a Command
LanguageExamplesComments
Bourne Shellif backup_script then echo "Backup succeeded." fi
C Shellif { backup_script } then echo "Backup succeeded." endif
Perlif (print "hello\n") { print "it worked\n"; } system "ls > /dev/null"; my $systemResponse = $? >> 8; if (!($systemResponse)) { print "it worked\n"; } else { print "it didn't work\n"; }
C
Visual Basic
Applescript
Top How to Define and Call Functions/Subroutines
LanguageExamplesComments
Bourne ShellBackup() { return `cp $1 /backups > /dev/null 2>&1` } Success() { echo "$1 was backed up. } if Backup ".login" then Success ".login" else echo "Backup failed!" fi Functions and Subroutines gets their args through a local $1, $2, etc. A function uses a return statement to indicate success or failure.
C Shell
Perlsub Albums { my $artist = shift; my @albums = @{$_[0]}; print "$artist: "; print join(", ", @albums); return scalar(@albums); } my @cnt = Albums("INXS", ["Kick", "X"]); print "\n@cnt albums\n"; Line-by-line, this shows the sub declaration, shifting in the first arg from @_, dereferencing the next arg from @_, a simple print, using join to quickly print an array, return the number of items in an array, and finally, something complex: using an anonymous array reference!
C
Visual Basic
Applescript-- test this! on sub1() set date to (do shell script "date") return date end sub1 set myDate to sub1() script sub2 display dialog "hi" end script tell sub2 to run
Top How to Get Input from the User
LanguageExamplesComments
Bourne Shellread foo
C Shellset foo=$<
Perlmy $input = <STDIN>; It's common to use "<>" as a shortcut, but that will first look for arguments on the command-line before looking at the terminal (STDIN), so use "<>"with care.
C
Visual Basic
Applescript
Top How to Capture the Output of a System Call
LanguageExamplesComments
Bourne Shellfilelist=`ls`
C Shellset filelist=`ls`
Perlmy $filelist = `ls`;
C
Visual Basic
Applescript
Top How to construct for loops
LanguageExamplesComments
Bourne Shellfilelist=`ls` for file in $filelist do cp $file $file.bak done
C Shellset filelist=`ls` foreach file ($filelist) cp $file $file.bak end
Perlfor (my $i = 0; $id <= $#myArray; $id++) ... foreach my $item (@myArray) ... foreach my $key (keys %myHash) ...
C
Visual Basic
Applescript
Top How to construct while loops
LanguageExamplesComments
Bourne Shellwhile [ $FLAG = "TRUE" ] do ... done
C Shellwhile ($FLAG == "TRUE") ... end
Perlwhile ($attempt < $MAX_ATTEMPTS) { ... }
C
Visual Basic
Applescript
Top How to construct case statements
LanguageExamplesComments
Bourne Shellcase $foo in "Hello") echo "Hello there!" ;; *) echo "Default case" ;; esac
C Shellswitch ($foo) case "Hello": ... # Use breaksw here, if desired default: ... endsw
Perluse Switch; switch ($val) { case 1 { print "Too low\n" } case 2 { print "Just right\n" } else { print "Too high\n" } } Case (or "switch") statements aren't built into Perl 5 - you'll need the Switch module from CPAN for this to work. Perl 6 provides a switch construct (using the terms "given", "when", and "default", in place of "switch", "case", and "else"). The Switch module provides a Perl 6 compatibility mode ("use Switch 'Perl6';"), but the "default" keyword seems broken when I try to use it.
C
Visual Basic
Applescript
Top How to use goto commands
LanguageExamplesComments
Bourne Shelln/a
C Shellif ($#argv <= 0)then goto noswitch endif ... noswitch: echo "Must supply argument(s)." exit
Perlif ($#ARGV <= 0) { goto switches; } print "Must supply argument(s)."; exit 1; switches: foreach my $arg (@ARGV) ... I've never actually used a goto in Perl, and hopefully I never will!
C
Visual Basic
Applescript
Top How to do Mathematical Calculations
LanguageExamplesComments
Bourne Shellcount=1 count=`expr $count + 1`
C Shellset count=1 set count=`expr $count + 1`
Perl$i++; $i = $i + 2;
C
Visual Basic
Applescript
Top How to Redirect Standard Out and Standard Error
LanguageExamplesComments
Bourne Shellbackupscript > /dev/null backup_script 2> /dev/null backup_script > logfile 2>&1 Redirects Standard Out only Redirects Standard Error only Redirects Standard Out and Error
C Shellbackupscript > /dev/null Redirects Standard Out and Standard Error
Perlopen (F, ">/var/logs/out"); print F "Process completed\n"; close(F); This is really just a method for printing directly to a file instead of "Standard Out". When a Perl script is called from a shell, you can use the shell's methods for redirecting Standard Out and/or Standard Error.
C
Visual Basic
Applescript
Top Links
General Links (edit)
  • Rosetta Stone for Scripting Languages (somewhat similar to this Primer)
  • Portable Shell Scripts (includes good comparisons between lots of shells!)
  • Brett Matson's Portable Coding Guideline (nice cross-platform stuff, esp. Perl versions of most UNIX commands)
  • LanguageLinks
    Bourne Shell Add links
    C Shell
    (edit these links)
  • Why you shouldn't program in C shell
  • Perl
    (edit these links)
  • Perl.com (Downloads and news from O'Reilly)
  • CPAN (download modules from the Comprehensive Perl Archive Network)
  • use Perl (news)
  • ActiveState's ActivePerl (nice Windows port!)
  • PerlDoc
  • ASPN's ActivePerl Docs
  • Rex Swain's Perl Guide
  • O'Reilly's Practical mod_perl Book Online
  • Perl Monks
  • DevShed Perl Forum
  • CGI Resource Index
  • Perl Archive
  • Matt's Script Archive
  • CGIexpo.com
  • CGI City
  • C Add links
    Visual Basic
    (edit these links)
  • Microsoft TechNet Script Center
  • Windows Script Technologies (MSDN)
  • Windows Script Host (WSH) Reference (MSDN)
  • Scripting Clinic Articles (MSDN)
  • VBA Language Reference (MSDN)
  • Simon Shepard's WSH Commands Overview
  • VB Forums
  • VB mode for Emacs
  • Applescript
    (edit these links)
  • Apple's AppleScript Language Guide
  • VBA-to-AppleScript Guide (good AppleScript basics, esp. for MS Office)
  • ScriptWeb
  • MacScripter and their AppleScript Sourcebook
  • MacCentral's AppleScript Primer
  • MacTech's VBA-to-AppleScript Guide