AppleScript_ The Definitive Guide - Matt Neuburg [219]
set theNum to text returned of (display dialog "Enter a number:" default answer "")
set t to path to temporary items
set posixT to POSIX path of t
set f to open for access file ((t as string) & "bctemp") with write permission
write "obase = 16\n" to f
write (theNum as string) & "\n" to f
write "quit\n" to f
close access f
set s to "/usr/bin/bc " & quoted form of (posixT & "bctemp")
display dialog (do shell script s)
(The text returned of display dialog is Unicode text in Tiger; I don't want to write Unicode text to the file, because bc won't be able to read it, so I coerce to a string.)
The Unix shell parsing and quotation rules can be something of a headache. A simple solution is to protect a string from the parsing rules completely by wrapping it in single quotes; AppleScript makes this easy with the quoted form property of a string (see "String Properties" in Chapter 13). But this does not absolve you from AppleScript's own rules for forming literal strings (see Table 13-1). So, for instance, in the system attribute example in "File and Machine Information" in Chapter 21, quotes are escaped in the literal string s, to get AppleScript to do the right thing; then the entire string is munged with quoted form to get the shell to do the right thing.
Using a file as an intermediary can simplify things. When talking to Perl, for example, there is no problem forming a short Perl script and handing it to Perl directly by means of the -e switch; but for a longer Perl script it might make sense to write it into a file and then tell Perl to run the file. The Perl script can be created on the fly, but often there is no need; it might make more sense to prepare it beforehand.
Here's an example. I write for the weekly online Macintosh journal TidBITS , whose archives are searchable online: their web site has a page (http://db.tidbits.com) where you can enter words to search for, returning a page of links to past articles containing those words. We'll simulate this page, acting as a web client ourselves, with the help of curl (a brilliant Internet client Unix tool—read the man pages for more information). We have researched the HTML format of the results page, and we've prepared a Perl script to parse it and extract the URLs and titles of the found articles. The Perl script expects as argument the pathname of the file containing the HTML:
$s = "";
while (<>) {
$s .= $_;
}
$s =~ m{search results (.*)$}si;
$1 =~ m{