Section 1.3. Calculation and Repetition


1.3. Calculation and Repetition

Computers are good at calculation and repetition . Humans, on the other hand, are liable to calculate inaccurately, and all the more so in the face of repetitive activity, which can make them careless, bored, and angry. Calculation and repetition on a computer should be performed by the computernot by a human.

Here's an example straight off the Internet, where someone writes: "I want to rename a whole lot of image files based on the names of the folders they're in." One's eyes glaze over at the prospect of doing this by hand. Yet with AppleScript, it's a snap. The task would make a good dropleta little application, written with AppleScript, with a Finder icon onto which you can drop files and folders you want processed. (More details appear in "Applet and Droplet" in Chapter 3 and "Applets" in Chapter 27.) Here's the AppleScript code for such a droplet; you drop a folder or folders onto its icon in the Finder, and it renames all items in each folder using that folder's name followed by a number:

 on open folderList     repeat with aFolder in folderList         if kind of (info for aFolder) is "Folder" then             renameStuffIn(aFolder)         end if     end repeat end open on renameStuffIn(theFolder)     set ix to 0     tell application "Finder"         set folderName to name of theFolder         set allItems to (get every item of theFolder)         repeat with thisItem in allItems             set ix to ix + 1             set newName to folderName & ix             set name of thisItem to newName         end repeat     end tell end renameStuffIn

The parameter folderList tells us what was dropped onto the droplet. We process each dropped item, starting with a sanity check to make sure it's really a folder. If it is, we give each item in the folder a new name based on the folder's name along with a number that increases each time.




AppleScript. The Definitive Guide
AppleScript: The Definitive Guide, 2nd Edition
ISBN: 0596102119
EAN: 2147483647
Year: 2006
Pages: 267
Authors: Matt Neuburg

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net