O'Reilly logo

Apple® Automator with AppleScript® Bible by Thomas Myer

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 11. AppleScript Subroutines

IN THIS CHAPTER

  • What are subroutines?

  • Defining a subroutine

  • Running a subroutine

  • Using loops, conditionals, and variables in subroutines

  • Recursive subroutines

  • Reusing subroutines

  • Some useful subroutines

So far, your AppleScript education has included learning about variables, operators, conditional statements, loops, and a few other details. However, you've only created simple scripts that run as standalone files — you haven't had the opportunity to create any scripts that are more complex, or any script that would require reusable code.

In this chapter, you're going to learn how to create and use (and reuse) subroutines to your advantage. Learning about subroutines will take your AppleScript knowledge to the next level.

Please note that many books on AppleScript refer to subroutines as handlers. Technically speaking, they're absolutely correct, but please note that in the AppleScript world, handlers can mean a lot of different things. For example, when you tell an application such as Safari to open, you're using an on handler.

Combining the on handler with a custom handler (or subroutine) that you've built yourself seems a bit confusing, especially if you have experience with shell scripting, Perl, Python, or Java, where custom subroutines are really a separate deal. For that reason, I insist on calling a custom handler a subroutine, just to avoid any possible confusion and to make it easier for programmers from other languages.

What Are Subroutines?

If you're ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required