Notes for CSC 254, October 11 and 16, 2012 A3 due Monday, 11:59pm Midterm next Thursday, in class. A4 will be passed out then. Bring questions to class on Tuesday. ---------------------------- Scripting languages What *is* a scripting language? glue extension text processing web (CGI, server-side, client-side, XSLT) Common characteristics economy of expression usually interpreted; for both batch and interactive use often a single canonical implementation lack of definitions; simple scoping rules dynamic typing, often lots of coercion high-level types: sets, bags, dictionaries, lists, tuples, objects easy access to other programs pattern matching and string manipulation One also hears talk of "dynamic languages," in reference to the use of dynamic typing. This is arguably a better / more useful term. Ancestors shells JCL sh/ksh/bash csh/tcsh DOS shell text processing RPG sed awk Modern categories general-purpose Rexx (old but still used on IBM platforms) late '70s Perl (probably the most widely used) late '80s Tcl (probably on the downswing, except for Tk) late '80s Python (gaining on Perl) early '90s Ruby (on the upswing) early '90s* * didn't really catch on in the West until good English documentation came out in 2001) AppleScript (Mac platform only) Visual Basic (Windows platform only) extension most of the general-purpose ones Python at Disney and ILM AOLServer w/ Tcl Scheme Elk SIOD -- leading extension lang for GIMP (Tcl, Python, Perl also supported) Guile Emacs Lisp proprietary Maya Cold Fusion AutoCAD Macromedia Director, Flash Adobe tools w/ JavaScript, AppleScript, or VBScript many, many others math APL S, R Mathematica, Matlab, Maple web CGI -- all the GP options PHP -- leading server-side option; also ASP JavaScript -- leading client side option (VB used w/in some orgs.) XSLT -- for processing XML ---------------------------- Perl "There's more than one way to do it." if ($a < $b) { $s = "less"; } $s = "less" if ($a < $b); $s = "less" unless ($b >= $a); heavy use of punctuation characters # comment #! convention script language identifier $, @, %, NAKED scalar, array, hash, filehandle <..> readline of file handle =~ pattern match $_ default input line and loop index . and .= concatenation | NB: sharp-bang ("shebang") tends to be non-portable. | Workaround: | #!/usr/bin/env perl | # ... | This looks up perl in $PATH. Still requires env to be in the same place | on every system (and it isn't always). It also opens a vulnerability if | there's more than one perl on your PATH. Dynamic typing, coercion $a = "4"; print $a . 3 . "\n"; prints 43 print $a + 3 . "\n"; prints 7 subroutines sub min { my $rtn = shift(@_); # first argument # my gives local lexical scope; @_ is list of arguments # local gives dynamic scope for my $val (@_) { $rtn = $val if ($val < $rtn) } return $rtn; } ... $smallest = min($a, $b, $c, $d, @more_vals); # args are flattened context some things behave differently in array and scalar "contexts". @my_array = @_; $num_args = @_; you can do this yourself: sub abs { my @args = @_; for (@args) { $_ = -$_ if ($_ < 0); # $_ is a reference; } # this modifies args in place return wantarray ? @args : $args[0]; # note: NOT @args[0] } ... print join (", ", abs(-10, 2, -3, 4, -5)), "\n"; print $n = abs(-10, 2, -3, 4, -5), "\n"; This prints 10, 2, 3, 4, 5 10 regular expressions $_ = "-3.14e+5"; # default subject of match if =~ not used if (/^([+-]?)((\d+)\.|(\d*)\.(\d+))(e([+-]?\d+))?$/) { # floating point number print "sign: ", $1, "\n"; print "integer: ", $3, $4, "\n"; print "fraction: ", $5, "\n"; print "mantissa: ", $2, "\n"; print "exponent: ", $7, "\n"; } This prints sign: - integer: 3 fraction: 14 mantissa: 3.14 exponent: +5 Hashes %complements = ("ref" => "cyan", "green" => "magenta", "blue" => "yellow"); # NB: => is (almost) an alias for , # (also forces its left operand to be interpreted as a string) print $complements{"blue"}; # yellow Examples from book (on overhead slides) HTML heading extraction #! while (<>) next, redo implicit matching against $_ update-assignment to $_ s/// -- could have been written $_ =~ s/// minimal matching via *? character sets in REs: [hH], [123] backslash escape of / capture with ( ) trailing s on match allows '.' to match embedded \n force quit @ARGV, $#ARGV die open, file handles pid command -w -w print with unlimited width (wide wide) -x include processes w/out controlling terminals -o'pid,command' what to print split trailing i on match ignores case $$ my process id ne (strings) vs != (numbers) beginning of line marker: ^ (and eol marker: $) built-ins for many common shell commands (kill, sleep) ---------------------------- | Emacs Lisp (not needed this year) | | Emacs has a C core, but most of its functionality is actually in Lisp. | Where to find documentation: M-x info | m Elisp | m Emacs Lisp Intro | | Best way to learn is probably to read existing code, consulting the | manual as necessary. Use M-:load-path to see where it all comes | from. | | load-file | eval-last-sexp | | buffer content | window rectangular screen real-estate | frame GUI holder for windows | | tons of built-in functions | manipulating buffers, windows, and frames | moving around | accessing outside resources | defining and executing commands | | (point) | markers | unlike numeric positions, these move with insertions and deletions | note that they impose overhead on the editor; zero them out when you're | done with them to avoid unnecessary overhead prior to GC | | interactive | very complex, baroque set of options, specifying how an interactive | command (one that can be bound to a keystroke) gets its arguments: | from a prefix (C-U num key) | from prompting in the minibuffer | from the position of the cursor | from the "mark" | from the character at the cursor | from subsequent keystrokes (up until a delimiter) | from a mouse event | may be optional, have defaults, do command completion | etc. | | save-excursion | message | | define-key | M-x | | Example from book: numbering lines | interactive in this case has | * raise exception if buffer is read-only | r start and end of "region" | \n separator | p prefix arg (starting line number) ---------------------------- Web scripting CGI scripts (common gateway interface)
or "get" ...
post delivers name=val pairs on stdin can be numerous not visible to user get delivers name-val pairs as part of URL can be bookmarked script output is displayed in browser disadvantages start-up (loading) cost of script no sandboxing of script behavior; has to be trusted dynamic nature visible to user need to print all the boilerplate HTML embedded scripts require server to look inside page source existence _invisible_ to user PHP dominates Perl derivative built-in support for access to script args ($_REQUEST). interaction with numerous database systems email MIME encoding security and authentication URI manipulation delimit with simple CGI replacement don't have to "print" the HTML parts self-posting action attribute names self; script looks to see whether it has a full set of args; prints original form if no, results if yes client-side scripts don't pay Internet overhead; can be much more interactive; also reduce load on server (even, e.g., for checking of input parameters) JavaScript dominates -- built into almost every browser mostly but not completely standard if you want local-only processing of FORM hijack submit behavior in
itself specify function to invoke in appropriate element specify code of function in header of HTML file grab arguments from and print results to fields of 'document' object, using names defined in the HTML document object model (DOM) Applets often in Java; also in Flash, Windows Media Player, PDF, other plug-ins give a separate script complete control of some subset of window real estate, unmediated by HTML example: require sandboxing XML medium-complexity markup language (simpler than SGML, more complex than HTML) more regular and structured than HTML syntax without semantics (unlike HTML) meant for representing all sorts of structured data requires semantic interpretation and formatting for display natural tree structure XHTML successor to HTML; compliant with XML well-formed: end tags for everything (or singletons) XSLT for processing XML pattern-match against trees XPATH provides naming conventions for elements of XML trees XSLT transforms XML into more XML, HTML, or whatever you want natural control flow is depth-first traversal of tree, but straightforward to program alternatives every template, when applied, has a notion of current node; naming is typically relative to that node XSL-FO can be used to display XML