Functions for Reusable Code

A function is something like an alias. We define the function, and then use it like a command. It helps break long programs up into manageable chunks, reducing the probability of bugs. And it is easy:

function xword {
    # cheat on crossword puzzles
    # to use: xword .ere..ip...
    # where the dots are letters you do not know
    grep "^$1$" /usr/share/dict/words

Here we create a function named xword and we define it as everything between the curly braces. The first 3 lines of the function are comments, and if you are placing them in a file, you should leave them for future reference. If you are typing them interactively at the command line, leave them out to save keystrokes.

The one line in the function that does something calls the command and tells it to find a certain pattern in the dictionary file at /usr/share/dict/words.

Here is what the pattern means. The caret (^) means start trying to match at the beginning of the word only. The dollar sign at the end means do not stop matching until the end of the word. The $1 in the middle means use the pattern that was in the first argument after the function name (xword).

So if you type xword .ere..ip… it will show you as many words as it finds (maybe none) that start with some letter, followed by ere, followed by two letters, then ip, and then three more letters. Try it.

Two more to try:

xword .st.i..


Printed from — Functions for Reusable Code.